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