JAVA - 工厂模式
1. 简单工厂违背OCP(Open Close Principle)原则 , 即对增加开放,对修改关闭。如果要符合OCP原则,要针对接口编程。
1 //简单工厂模式,违反了OCP原则 2 public class DAOFactory { 3 4 public static IAddressDao getAddressDao() { 5 return new AddressDao(); 6 } 7 8 public static IUserDao getUserDao() { 9 return new UserDao(); 10 } 11 12 }
2.下一种模式的工厂进一步优化了简单工厂,但有一个缺点就是依赖于工厂的实现类
1 public interface IFactoryDao { 2 public IUserDao createUserDao(); 3 public IAddressDao createAddressDao(); 4 }
1 public class MysqlDaoFactory implements IFactoryDao { 2 private static IFactoryDao factory = new MysqlDaoFactory(); 3 private MysqlDaoFactory() { } 4 5 public static IFactoryDao getInstance() { 6 return factory; 7 } 8 9 @Override 10 public IAddressDao createAddressDao() { 11 return new AddressDao(); 12 } 13 14 @Override 15 public IUserDao createUserDao() { 16 return new UserDao(); 17 } 18 }
1 public class OracleDaoFactory implements IFactoryDao { 2 private static IFactoryDao f = new OracleDaoFactory(); 3 private OracleDaoFactory(){} 4 5 public static IFactoryDao getInstance() { 6 return f; 7 } 8 @Override 9 public IUserDao createUserDao() { 10 return new UserOracleDao(); 11 } 12 13 @Override 14 public IAddressDao createAddressDao() { 15 return new AddressOracleDao(); 16 } 17 18 }
3.为了解决第二种工厂模式的弊端,需要使用配置文件,然后通过反射获取工厂实例
dao.properties 配置文件
factory=dawang.dao.MysqlDaoFactory
1 package dawang.util; 2 3 import dawang.dao.IFactoryDao; 4 5 import java.lang.reflect.InvocationTargetException; 6 import java.lang.reflect.Method; 7 import java.util.Properties; 8 9 public class DaoUtil { 10 public static void main(String[] args) { 11 System.out.println(createDaoFactory()); 12 } 13 @SuppressWarnings({ "rawtypes", "unchecked" }) 14 public static IFactoryDao createDaoFactory() { 15 IFactoryDao f = null; 16 try { 17 Properties prop = PropertiesUtil.getDaoProp(); 18 String fs = prop.getProperty("factory"); 19 Class clz = Class.forName(fs); 20 String mn = "getInstance"; 21 Method m = clz.getMethod(mn); 22 f = (IFactoryDao)m.invoke(clz); 23 } catch (ClassNotFoundException e) { 24 e.printStackTrace(); 25 } catch (SecurityException e) { 26 e.printStackTrace(); 27 } catch (NoSuchMethodException e) { 28 e.printStackTrace(); 29 } catch (IllegalArgumentException e) { 30 e.printStackTrace(); 31 } catch (IllegalAccessException e) { 32 e.printStackTrace(); 33 } catch (InvocationTargetException e) { 34 e.printStackTrace(); 35 } 36 return f; 37 } 38 }
posted on 2017-07-05 22:22 dawangandy 阅读(90) 评论(0) 收藏 举报
浙公网安备 33010602011771号