03.设计模式_抽象工厂模式(Abstract Fcatory)
2015-03-19 01:04
309 查看
抽象工厂模式:创建一些列相关或者互相依赖的对象的接口,而无需指定他们具体的类,
1、创建工厂Factory:
2.在service中调用工厂类创建对象
3.dao.properties
4.EmployeeDao.java
1、创建工厂Factory:
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中调用工厂类创建对象
package patterns.design.factory; import java.util.List; public class BusinessService { // service 的方法取决于功能 private EmployeeDao employeeDao; public BusinessService() { // 自己创建对象 // 调用 工厂类获得一个dao对象 this.employeeDao = DaoFactory.newDaoFactory().newEmplyeeDao(); } //查看所有员工 public List getAllEmployees() { return employeeDao.getAll(); } }
3.dao.properties
employeeDaoClassname=patterns.design.factory.EmployeeDaoImpl
4.EmployeeDao.java
package patterns.design.factory; import java.util.List; public interface EmployeeDao { public List getAll(); }
相关文章推荐
- Java与设计模式(03)--抽象工厂模式
- Java设计模式圣经连载(03)-抽象工厂模式
- java设计模式03_抽象工厂模式
- C#设计模式之工厂模式(Factory)--03 抽象工厂模式(Abstract Factory)
- 设计模式学习03—抽象工厂模式
- 设计模式学习03—抽象工厂模式
- 设计模式03_抽象工厂模式
- 设计模式-03-抽象工厂模式
- Java设计模式圣经连载(03)-抽象工厂模式
- Java设计模式圣经连载(03)-抽象工厂模式
- 设计模式之03抽象工厂模式(笔记)
- 设计模式(03) 抽象工厂模式(下)
- Python实现设计模式--03.抽象工厂模式(Abstract Factory Pattern)
- 设计模式学习笔记(三)——Abstract Factory抽象工厂模式
- 设计模式C#描述——抽象工厂模式
- 设计模式 - Abstract Factory Pattern(抽象工厂模式)
- 乐在其中设计模式(C#) - 抽象工厂模式(Abstract Factory Pattern)
- 乐在其中设计模式(C#) - 抽象工厂模式(Abstract Factory Pattern)
- .NET设计模式(3):抽象工厂模式(Abstract Factory)(转)
- 设计模式杂谈:创建型模式之抽象工厂模式(Abstract Factory)