23种设计模式之抽象工厂模式
抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
package designMode.abstractFactory; class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package designMode.abstractFactory; class Dept { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } }
package designMode.abstractFactory; interface IUser { void insert(User user); User getUser(int id); }
package designMode.abstractFactory; interface IDept { void insertDept(Dept dept); Dept getDept(int id); }
package designMode.abstractFactory; class OracleUser implements IUser{ @Override public void insert(User user) { System.out.println("在Oracle数据库中给user表新增一条记录!"); } @Override public User getUser(int id) { System.out.println("在Oracle数据库中根据用户id得到user表一条记录!"); return null; } }
package designMode.abstractFactory; class OracleDept implements IDept{ @Override public void insertDept(Dept dept) { System.out.println("在Oracle数据库中给dept表新增一条记录!"); } @Override public Dept getDept(int id) { System.out.println("在Oracle数据库中根据id获取dept表中的一条记录!"); return null; } }
package designMode.abstractFactory; class MysqlUser implements IUser{ @Override public void insert(User user) { System.out.println("在Mysql数据库中给user表新增一条记录!"); } @Override public User getUser(int id) { System.out.println("在Mysql数据库中根据用户id得到user表的一条记录!"); return null; } }
package designMode.abstractFactory; class MysqlDept implements IDept{ @Override public void insertDept(Dept dept) { System.out.println("在Mysql数据库中给dept表新增一条记录!"); } @Override public Dept getDept(int id) { System.out.println("在Mysql数据库中根据id获取dept表的一条记录!"); return null; } }
package designMode.abstractFactory; interface IFactory { IUser createUser(); IDept createDept(); }
package designMode.abstractFactory; class OracleFactory implements IFactory{ @Override public IUser createUser() { return new OracleUser(); } @Override public IDept createDept() { return new OracleDept(); } }
package designMode.abstractFactory; class MysqlFactory implements IFactory{ @Override public IUser createUser() { return new MysqlUser(); } @Override public IDept createDept() { return new MysqlDept(); } }
package designMode.abstractFactory; class Test { public static void main(String[] args) { User user = new User(); Dept dept = new Dept(); //IFactory factory = new OracleFactory(); IFactory factory = new MysqlFactory(); IUser iu = factory.createUser(); iu.insert(user); iu.getUser(1); IDept id = factory.createDept(); id.insertDept(dept); id.getDept(1); } }