简单工厂模式
简单工厂的本质是:选择实现(用户不需要知道具体的实现类的信息,只需要调用接口使用即可。)
代码目录:
Api.java:
package a;
public interface Api {
public void test1(String s);
}
Client.java:
package a;
public class Client {
public static void main(String[] args){
Api api=Factory.createApi();
api.test1("ggggg");
}
}
Impl.java:
package a;
public class Impl implements Api{
public void test1(String s){
System.out.println("impl1 is "+s);
}
}
Factory.java:()
package a; import java.io.IOException; import java.io.InputStream; import java.util.Properties; //工厂类,用来创建Api对象 public class Factory { public static Api createApi(){ //直接读取配置文件来获取需要创建实例的类 Properties p=new Properties(); InputStream in =null; try{ in=Factory.class.getResourceAsStream("FactoryTest.properties"); p.load(in); }catch (IOException e){ System.out.println("error"); e.printStackTrace(); }finally{ try{ in.close(); }catch (IOException e){ e.printStackTrace(); } } //用反射去创建 Api api=null; try{ api=(Api)Class.forName(p.getProperty("ImplClass")).newInstance(); }catch (InstantiationException e){ e.printStackTrace(); }catch (IllegalAccessException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); } return api; } }
FactoryTest.properties:
(配置文件,添加新类的时候,只需要更改配置文件即可,其他程序都不需要改动。)
ImplClass=a.Impl
运行结果:
impl1 is ggggg

浙公网安备 33010602011771号