1 16 17 package com.google.inject.example; 18 19 import static junit.framework.Assert.assertTrue; 20 21 24 public class ClientServiceWithFactories { 25 26 28 public interface Service { 29 void go(); 30 } 31 32 public static class ServiceImpl implements Service { 33 public void go() { 34 } 36 } 37 38 public static class ServiceFactory { 39 40 private ServiceFactory() {} 41 42 private static Service instance = new ServiceImpl(); 43 44 public static Service getInstance() { 45 return instance; 46 } 47 48 public static void setInstance(Service service) { 49 instance = service; 50 } 51 } 52 53 public static class Client { 54 55 public void go() { 56 Service service = ServiceFactory.getInstance(); 57 service.go(); 58 } 59 } 60 61 public void testClient() { 62 Service previous = ServiceFactory.getInstance(); 63 try { 64 final MockService mock = new MockService(); 65 ServiceFactory.setInstance(mock); 66 Client client = new Client(); 67 client.go(); 68 assertTrue(mock.isGone()); 69 } 70 finally { 71 ServiceFactory.setInstance(previous); 72 } 73 } 74 75 public static class MockService implements Service { 76 77 private boolean gone = false; 78 79 public void go() { 80 gone = true; 81 } 82 83 public boolean isGone() { 84 return gone; 85 } 86 } 87 88 public static void main(String [] args) { 89 new ClientServiceWithFactories().testClient(); 90 } 91 } 92 | Popular Tags |