美文网首页
工厂模式

工厂模式

作者: 海阔天空cqk | 来源:发表于2019-10-10 17:29 被阅读0次

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

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

    相关文章

      网友评论

          本文标题:工厂模式

          本文链接:https://www.haomeiwen.com/subject/umsapctx.html