1 16 17 package com.google.inject.example; 18 19 import static junit.framework.Assert.assertTrue; 20 import junit.framework.Assert; 21 22 25 public class ClientServiceWithDependencyInjection { 26 27 29 public interface Service { 30 void go(); 31 } 32 33 public static class ServiceImpl implements ClientServiceWithDependencyInjection.Service { 34 public void go() { 35 } 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 [] args) { 94 new ClientServiceWithDependencyInjection().testClient(); 95 } 96 } 97 | Popular Tags |