JAVA - 工厂模式

时间:2023-03-08 17:16:12
JAVA - 工厂模式

1. 简单工厂违背OCP(Open Close Principle)原则 , 即对增加开放,对修改关闭。如果要符合OCP原则,要针对接口编程。

 //简单工厂模式,违反了OCP原则
public class DAOFactory { public static IAddressDao getAddressDao() {
return new AddressDao();
} public static IUserDao getUserDao() {
return new UserDao();
} }

2.下一种模式的工厂进一步优化了简单工厂,但有一个缺点就是依赖于工厂的实现类

 public interface IFactoryDao {
public IUserDao createUserDao();
public IAddressDao createAddressDao();
}
 public class MysqlDaoFactory implements IFactoryDao {
private static IFactoryDao factory = new MysqlDaoFactory();
private MysqlDaoFactory() { } public static IFactoryDao getInstance() {
return factory;
} @Override
public IAddressDao createAddressDao() {
return new AddressDao();
} @Override
public IUserDao createUserDao() {
return new UserDao();
}
}
 public class OracleDaoFactory implements IFactoryDao {
private static IFactoryDao f = new OracleDaoFactory();
private OracleDaoFactory(){} public static IFactoryDao getInstance() {
return f;
}
@Override
public IUserDao createUserDao() {
return new UserOracleDao();
} @Override
public IAddressDao createAddressDao() {
return new AddressOracleDao();
} }

3.为了解决第二种工厂模式的弊端,需要使用配置文件,然后通过反射获取工厂实例

dao.properties 配置文件

factory=dawang.dao.MysqlDaoFactory
 package dawang.util;

 import dawang.dao.IFactoryDao;

 import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties; public class DaoUtil {
public static void main(String[] args) {
System.out.println(createDaoFactory());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static IFactoryDao createDaoFactory() {
IFactoryDao f = null;
try {
Properties prop = PropertiesUtil.getDaoProp();
String fs = prop.getProperty("factory");
Class clz = Class.forName(fs);
String mn = "getInstance";
Method m = clz.getMethod(mn);
f = (IFactoryDao)m.invoke(clz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return f;
}
}