抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
结构图:
代码如下:
1 public class AbstractFactoryTest { 2 public static void main(String[] args) { 3 User user = new User(); 4 Department department = new Department(); 5 6 IUser iuser = DataAccess.createUser(); //直接得到数据访问实力,而不存在任何依赖 7 iuser.insertUser(user); 8 iuser.getUser("id"); 9 10 IDepartment idepartment = DataAccess.createDepartment(); 11 idepartment.insertDepartment(department); 12 idepartment.getDepartment("id"); 13 } 14 15 }
1 package com.cai.designMethods.abstractFactory; 2 3 public class DataAccess { 4 private static final String bd = "Sqlserver"; //数据库名 可换成Access 5 6 public static IUser createUser(){ 7 IUser user = null; 8 if("Sqlserver".equals(bd)){ 9 user = new SqlserverUser(); 10 }else if("Access".equals(bd)){ 11 user = new AccessUser(); 12 } 13 return user; 14 } 15 16 public static IDepartment createDepartment(){ 17 IDepartment departmrnt = null; 18 if("Sqlserver".equals(bd)){ 19 departmrnt = new SqlserverDepartment(); 20 }else if("Access".equals(bd)){ 21 departmrnt = new AccessDepartment(); 22 } 23 return departmrnt; 24 } 25 26 }
1 public interface IUser { 2 int insertUser(User user); 3 User getUser(String id); 4 5 }
1 public class AccessUser implements IUser { 2 3 @Override 4 public int insertUser(User user) { 5 // TODO Auto-generated method stub 6 return 0; 7 } 8 9 @Override 10 public User getUser(String id) { 11 // TODO Auto-generated method stub 12 return null; 13 } 14 15 }
1 public class SqlserverUser implements IUser { 2 3 @Override 4 public int insertUser(User user) { 5 // TODO Auto-generated method stub 6 return 0; 7 } 8 9 @Override 10 public User getUser(String id) { 11 // TODO Auto-generated method stub 12 return null; 13 } 14 15 }
1 public interface IDepartment { 2 int insertDepartment(Department department); 3 User getDepartment(String id); 4 }
1 public class AccessDepartment implements IDepartment { 2 3 @Override 4 public int insertDepartment(Department department) { 5 return 0; 6 } 7 8 @Override 9 public User getDepartment(String id) { 10 return null; 11 } 12 13 }
1 public class SqlserverDepartment implements IDepartment { 2 3 @Override 4 public int insertDepartment(Department department) { 5 // TODO Auto-generated method stub 6 return 0; 7 } 8 9 @Override 10 public User getDepartment(String id) { 11 // TODO Auto-generated method stub 12 return null; 13 } 14 15 }
1 public class User { 2 3 }
1 public class Department { 2 3 }