工厂方法模式使用的频率非常高,在我们日常的开发中总能见到它的身影。其定义为:
Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses.(定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。)
public abstract class Product {
public void method1(){}
public abstract void method2();
}
public class ConcreteProduct1 extends Product {
public void method2() {}
}
public class ConcreteProduct2 extends Product {
public void method2() {}
}
public abstract class Creator {
public abstract <T extends Product> createProduct(Class<T> clazz);
}
public class ConcreteCreator extends Creator {
public <T extends Product> createProduct(Class<T> clazz) {
Product product = null;
try {
product = (Product)Class.forName(clazz.getName()).newInstance();
} catch(Exeception e) {
}
return (T)product;
}
}
简单工厂模式
public class ObjectFactory<T> {
private final static Map<String, IDao<?>> DAO_MAP = Maps.newHashMap();
private static final String DEFAULT_PROPERTIES_FILE_NAME = "beans.properties";
static {
// 加载配置文件
Properties properties = new Properties();
try {
properties
.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_FILE_NAME));
if (CollectionUtils.isEmpty(properties.keySet())) {
throw new RuntimeException("properties is empty");
}
for (Object key : properties.keySet()) {
Object o = properties.get(key.toString());
Class<?> clazz = Class.forName(o.toString());
DAO_MAP.put(key.toString(), (IDao<?>)clazz.newInstance());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static IDao<?> getDaoByName(String name) {
return DAO_MAP.getOrDefault(name, null);
}
}
public class StudentDaoImpl implements IDao<Student> {
@Override
public boolean save(Student o) {
System.out.println("StudentDaoImpl.save");
System.out.println(o);
return true;
}
@Override
public int update(Student o) {
System.out.println("StudentDaoImpl.update");
return 0;
}
@Override
public boolean delete(Student o) {
System.out.println("StudentDaoImpl.delete");
return false;
}
@Override
public Student selectById(String id) {
System.out.println("StudentDaoImpl.selectById");
return null;
}
}
public class TeacherDaoImpl implements IDao<Teacher> {
@Override
public boolean save(Teacher o) {
System.out.println("TeacherDaoImpl.save");
return false;
}
@Override
public int update(Teacher o) {
System.out.println("TeacherDaoImpl.update");
return 0;
}
@Override
public boolean delete(Teacher o) {
System.out.println("TeacherDaoImpl.delete");
return false;
}
@Override
public Teacher selectById(String id) {
System.out.println("TeacherDaoImpl.selectById");
return null;
}
}
bean.properties
studentDao=com.yxxmg.gof.create.pattern.factory.impl.StudentDaoImpl
teacherDao=com.yxxmg.gof.create.pattern.factory.impl.TeacherDaoImpl
https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/create/pattern/abstractfactory