抽象工厂模式:创建一些列相关或者互相依赖的对象的接口,而无需指定他们具体的类,
1、创建工厂Factory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | package patterns.design.factory; import java.io.InputStream; import java.util.Properties; public class DaoFactory { // 单例 private DaoFactory(){ try { // 读配置文件获得实现类 类名 Properties props = new Properties(); InputStream in = DaoFactory. class .getClassLoader() .getResourceAsStream( "dao.properties" ); props.load(in); this .employeeDaoClassname = props.getProperty( "employeeDaoClassname" ); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } private static DaoFactory instance = new DaoFactory(); public static DaoFactory newDaoFactory() { return instance; } private String employeeDaoClassname; // 提供方法返回实例对象dao public EmployeeDao newEmplyeeDao() { try { // 反射创建对象 EmployeeDao employeeDao = (EmployeeDao) Class.forName( this .employeeDaoClassname).newInstance(); return employeeDao; } catch (Exception e) { throw new RuntimeException(e); } } } |
2.在service中调用工厂类创建对象
1 package patterns.design.factory; 2 3 import java.util.List; 4 5 6 public class BusinessService { 7 8 // service 的方法取决于功能 9 private EmployeeDao employeeDao; 10 11 public BusinessService() { 12 // 自己创建对象 13 // 调用 工厂类获得一个dao对象 14 this.employeeDao = DaoFactory.newDaoFactory().newEmplyeeDao(); 15 } 16 17 18 //查看所有员工 19 public List getAllEmployees() { 20 return employeeDao.getAll(); 21 } 22 23 24 }
3.dao.properties
employeeDaoClassname=patterns.design.factory.EmployeeDaoImpl
4.EmployeeDao.java
1 package patterns.design.factory; 2 import java.util.List; 3 public interface EmployeeDao { 4 public List getAll(); 5 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步