Android中遇到的简单工厂模式的几种实现

废话一大堆:工厂模式有简单工厂模式,工厂方法模式 抽象工厂模式这三种工厂模式各自有各自的应用场景,根据需要灵活选择。

简单工厂模式实现1:

定义一个School接口

public interface School {
        StudentOne getStundent();
}

 定义接口实现类

public class SchoolImpl implements School {
    @Override
    public StudentOne getStundent() {
        StudentOne studentOne  =new StudentOne("小明","三班");
        return studentOne;
    }
}

Demo

      School schoolInterface = new SchoolImpl();
        schoolInterface.getStundent();

2.根据参数生产不通的实现

 定义接口实现类Two

public class SchoolImpl_Two implements School {
    @Override
    public StudentOne getStundent() {
        StudentOne studentOne = new StudentOne("小兰","四班");
        return studentOne;
    }
}

定义一个工厂类传入需要的参数

public class ParameterFactory {

    public static School getStudent(int parameter){
        switch (parameter){
            case 1 :
                 School school = new SchoolImpl();
                return school;
            case 2:
                return  new SchoolImpl_Two();
        }
        return  null;
    }
}

Demo:

        School school1 = ParameterFactory.getStudent(2);
        school1.getStundent();

3.根据配置文件产生不同的实现

添加配置文件config.properties

create_a=com.example.moveso.factory.impl.SchoolImpl
create_b=com.example.moveso.factory.impl.SchoolImpl_Two

定义配置文件读取类

public class PropertiesFactory {

    public static School whoAtSchool(Context context, String key) {
        Properties properties = new Properties();
        try {
            InputStream inputStream = context.getAssets().open("config.properties");
            //如果放入了app/src/mian/res/raw文件中
//        InputStream inputStream1 =      context.getResources().openRawResource("config.properties");
       //java写法
//        InputStream inputStream2 = PropertieaFactory.class.getResourceAsStream("assets/config.properties");
            properties.load(inputStream);
            Class clazz = Class.forName(properties.getProperty(key));
            return (School) clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

demo实现:

 School school = PropertiesFactory.whoAtSchool(this,"create_a");
        school.getStundent();
        School school2 = PropertiesFactory.whoAtSchool(this,"create_b");
        school2.getStundent();

代买写的比较乱以后会改进,根据需求3种方式实现的简单工厂模式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章