工厂模式

用于生成一个类实例,解耦。要生成对象有变时,只修改工厂方法即可。

Person.java 

Api {    Person create();}

ApiImpl implements Api{

    person create(){    return new Person();

 }}

------------------常规写法:--------------------------------

Api api = new ApiImpl();

Person person = api.create();

-----------------简单工厂:--------------------------------

SimpleFactory{  Api createApi(){  return new ApiImpl();

}}

Api api = new SimpleFactory().createApi();

Person person = api.create();

------------------参数方式:-------------------------------

ParameterFactory{  Api createApi(int type){  

   switch(type){case 1:return new ApiImpl();

}}

Api api = new ParameterFactory().createApi();

Person person = api.create();

-----------------配置文件方式:---------------------------------------

PropertiesFactory{ Api createApi(Context context){ 

     Properties prop = new Properties();

    //assets 目录下 config.properties

    InpusStream ins = context.getAssets.open("config.properties");

    //raw 目录下 config.properties

    InpusStream ins = context.getResource.openRawResource("config.properties");

    //java方式,不依赖context

    InputStream ins = PropertiesFactoty.class.getResourceAsStream("/assets/config.properties");

    prop.load(ins);

    Class clazz = Class.forName(prop.getProperty("xxx"));

return (Api)clazz;

}}

Api api = new PropertiesFactory().createApi();

Person person = api.create();

你可能感兴趣的:(工厂模式)