01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: */package com.google.inject.example;
16:
17: import static junit.framework.Assert.assertTrue;
18: import junit.framework.Assert;
19:
20: /**
21: * @author crazybob@google.com (Bob Lee)
22: */
23: public class ClientServiceWithDependencyInjection {
24:
25: // 62 lines
26:
27: public interface Service {
28: void go();
29: }
30:
31: public static class ServiceImpl implements
32: ClientServiceWithDependencyInjection.Service {
33: public void go() {
34: // ...
35: }
36: }
37:
38: public static class ServiceFactory {
39:
40: private ServiceFactory() {
41: }
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:
68: public static Client getInstance() {
69: Service service = ServiceFactory.getInstance();
70: return new Client(service);
71: }
72: }
73:
74: public void testClient() {
75: MockService mock = new MockService();
76: Client client = new Client(mock);
77: client.go();
78: assertTrue(mock.isGone());
79: }
80:
81: public static class MockService implements Service {
82:
83: private boolean gone = false;
84:
85: public void go() {
86: gone = true;
87: }
88:
89: public boolean isGone() {
90: return gone;
91: }
92: }
93:
94: public static void main(String[] args) {
95: new ClientServiceWithDependencyInjection().testClient();
96: }
97: }
|