工厂模式

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

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();

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容