简单工厂模式-静态工厂方法

接口的思想就是“封装隔离”。接口是系统可插拔性的保证。
1.优先使用接口
2.在既要定义子类的行为,又要为子类提供公共的功能时选择抽象类。 

public interface Api {
  public void operation(String s);
}  

public class ImplA implements Api {
  public void operation(String s) {
    System.out.println("ImplA" + s);
  }
}
                                         public class ImplB implements Api {
  public void operation(String s) {
    System.out.println("ImplB" + s);
  }
}                                        

public class Factory {
 //私有构造器,避免客户端无谓地创造简单工厂实例
 private Factory(){}
  public static Api createApi(int condition) {
    Api api = null;
    if(condition == 1) {
      api = new ImplA;
    } else if(condition == 2) {
      api = new ImplB;
    }
    return api;
  }
}                                                                                
在客户端使用时就可以用下面代码:
Api api = Factory.createApi(1);  

简单工厂也可以来创建抽象类或者普通类的实例。

缺点:
客户端调用工厂时传入参数,就说明客户端知道每个参数的含义。暴露了一部分细节。 

利用发射加上配置文件
Properties p = new Properties();
InputStream in = Test.class.getResourceAsStream("Design.properties");
p.load(in);

api = (Api)Class.forName(p.getProperty("ImplClass")).newInstance();

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

猜你喜欢

转载自katy1206.iteye.com/blog/2026078