KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > example > ClientServiceWithDependencyInjection


1 /**
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package com.google.inject.example;
18
19 import static junit.framework.Assert.assertTrue;
20 import junit.framework.Assert;
21
22 /**
23  * @author crazybob@google.com (Bob Lee)
24  */

25 public class ClientServiceWithDependencyInjection {
26
27 // 62 lines
28

29 public interface Service {
30   void go();
31 }
32
33 public static class ServiceImpl implements ClientServiceWithDependencyInjection.Service {
34   public void go() {
35     // ...
36
}
37 }
38
39 public static class ServiceFactory {
40
41   private ServiceFactory() {}
42
43   private static final Service service = new ServiceImpl();
44
45   public static Service getInstance() {
46     return service;
47   }
48 }
49
50 public static class Client {
51
52   private final Service service;
53
54   public Client(Service service) {
55     this.service = service;
56   }
57
58   public void go() {
59     service.go();
60   }
61 }
62
63 public static class ClientFactory {
64
65   private ClientFactory() {}
66
67   public static Client getInstance() {
68     Service service = ServiceFactory.getInstance();
69     return new Client(service);
70   }
71 }
72
73 public void testClient() {
74   MockService mock = new MockService();
75   Client client = new Client(mock);
76   client.go();
77   assertTrue(mock.isGone());
78 }
79
80 public static class MockService implements Service {
81
82   private boolean gone = false;
83
84   public void go() {
85     gone = true;
86   }
87
88   public boolean isGone() {
89     return gone;
90   }
91 }
92
93   public static void main(String JavaDoc[] args) {
94     new ClientServiceWithDependencyInjection().testClient();
95   }
96 }
97
Popular Tags