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:
19: /**
20: * @author crazybob@google.com (Bob Lee)
21: */
22: public class ClientServiceWithFactories {
23:
24: // 58 lines
25:
26: public interface Service {
27: void go();
28: }
29:
30: public static class ServiceImpl implements Service {
31: public void go() {
32: // ...
33: }
34: }
35:
36: public static class ServiceFactory {
37:
38: private ServiceFactory() {
39: }
40:
41: private static Service instance = new ServiceImpl();
42:
43: public static Service getInstance() {
44: return instance;
45: }
46:
47: public static void setInstance(Service service) {
48: instance = service;
49: }
50: }
51:
52: public static class Client {
53:
54: public void go() {
55: Service service = ServiceFactory.getInstance();
56: service.go();
57: }
58: }
59:
60: public void testClient() {
61: Service previous = ServiceFactory.getInstance();
62: try {
63: final MockService mock = new MockService();
64: ServiceFactory.setInstance(mock);
65: Client client = new Client();
66: client.go();
67: assertTrue(mock.isGone());
68: } finally {
69: ServiceFactory.setInstance(previous);
70: }
71: }
72:
73: public static class MockService implements Service {
74:
75: private boolean gone = false;
76:
77: public void go() {
78: gone = true;
79: }
80:
81: public boolean isGone() {
82: return gone;
83: }
84: }
85:
86: public static void main(String[] args) {
87: new ClientServiceWithFactories().testClient();
88: }
89: }
|