Home | History | Annotate | Download | only in example
      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 ClientServiceWithFactories {
     25 
     26 // 58 lines
     27 
     28 public interface Service {
     29   void go();
     30 }
     31 
     32 public static class ServiceImpl implements Service {
     33   public void go() {
     34     // ...
     35   }
     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