实现简单的工厂模式有两种方式
- 代码传参形式
- 配置文件形式
首先准备好一个实体类Student.java。代码如下:
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
再准备一个接口Api.java。代码如下:
public interface Api {
Student createStudent();
}
接口提供了内部创建Student的方法。
一、代码传参形式
创建工具类,主要是返回Api接口对象,代码如下:
public static Api createApi2(final String tag){
return new Api() {
@Override
public Student createStudent() {
switch (tag) {
case "A":
Student studentA = new Student("333");
Log.e("studentA",studentA.toString());
return studentA;
case "B":
Student studentB = new Student("333");
Log.e("studentB",studentB.toString());
return studentB;
}
return null;
}
};
}
方法中传递tag参数用于区分需要创建的Student对象。activity中调用该方法,就会返回一个Api的引用,调用api.createStudent()方法,就能得到当前Student实例对象。
Api api2 = FactoryModel.createApi2("A");
if(api2 != null) api2.createStudent();
二、配置文件
1、在main目录下创建assets文件夹,创建factory.properties配置文件,配置文件内容如下:
factory_A = com.xinyartech.factorymode.FactoryImplA
factory_B = com.xinyartech.factorymode.FactoryImplB
配置文件是以键值对的形式存储类名。
2、创建工具类,同理返回Api对象。代码如下:
public static Api createApi(Context context){
try{
//读取配置文件
Properties properties = new Properties();
InputStream is = context.getAssets().open("factory.properties");
properties.load(is);
//根据key读取类名
String factory_b = properties.getProperty("factory_B");
Class clazz = Class.forName(factory_b);
return (Api) clazz.newInstance();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
首先读取并加载配置文件,根据键获取类名。通过类名获取当前类clazz,根据clazz.newInstance()创建类的对象。activity中调用该方法,就会返回一个Api的引用,调用api.createStudent()方法,同样能得到当前Student实例对象。