工廠模式的核心:提供一個創(chuàng)建對象的功能蠢熄,不需要關系具體實現(xiàn),降低模塊之間的耦合度
案例:創(chuàng)建UserInfo對象
1炉旷、創(chuàng)建UserInfo類
public class UserInfo {
public UserInfo() {
}
public UserInfo(String name) {
this.name = name;
}
public UserInfo(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2签孔、定義創(chuàng)建UserInfo的接口
public interface UserApi {
UserInfo create();
}
3、接口實現(xiàn)
UserApiImpl.class
public class UserApiImpl implements UserApi {
@Override
public UserInfo create() {
return new UserInfo("",0);
}
}
UserApiImpl_A.class
public class UserApiImpl_A implements UserApi {
@Override
public UserInfo create() {
return new UserInfo("A",22);
}
}
UserApiImpl_B.class
public class UserApiImpl_B implements UserApi {
@Override
public UserInfo create() {
return new UserInfo("B",23);
}
}
4窘行、簡單工廠實現(xiàn):
public class SimpleFactory {
public static UserApi createUserApi(){
return new UserApiImpl();
}
}
簡單工廠調用:
UserApi userApi = SimpleFactory.createUserApi();
UserInfo user = userApi.create();
System.out.println("SimpleFactory -->"+user.toString());
5饥追、參數(shù)工廠實現(xiàn):
public class ParamterFactory {
public static UserApi createApi(int parameter){
switch (parameter){
case 1:
return new UserApiImpl_A();
case 2:
return new UserApiImpl_B();
}
return new UserApiImpl();
}
}
調用:
src/main/assets/config.properties
UserApi userApi = ParamterFactory.createApi(1);
UserInfo user = userApi.create();
System.out.println("ParameterFactory -->"+user.toString());
6、配置文件工廠實現(xiàn):
create_a=com.example.factory.impl.UserApiImpl_A
create_b=com.example.factory.impl.UserApiImpl_B
public class PropertiesFactory {
public static UserApi createApi(Context context){
Properties props = new Properties();
Class<?> clazz = null;
try {
//app/src/main/assets
InputStream inputStream = context.getAssets().open("config.properties");
props.load(inputStream);
clazz = Class.forName(props.getProperty("create_b"));
return (UserApi)clazz.newInstance();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
}
調用:
UserApi userApi = PropertiesFactory.createApi(this);
UserInfo user = userApi.create();
Log.d("PropertiesFactory -->",user.toString());