03.创建型————抽象工厂模式
package Create.c.AbstractFactory; //业务接口 public interface Salary { void calcSalary(); }
package Create.c.AbstractFactory; //业务接口 public interface Tax { void calcTax(); }
package Create.c.AbstractFactory; //业务实现类 public class HeBeiTax implements Tax { @Override public void calcTax() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的税收!"); } }
package Create.c.AbstractFactory; //业务实现类 public class HeBeiSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的薪资!"); } }
package Create.c.AbstractFactory; //业务实现类 public class GuangDongTax implements Tax { @Override public void calcTax() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的税收!"); } }
package Create.c.AbstractFactory; //业务实现类 public class GuangDongSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的薪资!"); } }
package Create.c.AbstractFactory; //工厂接口 public interface Factory { Salary createSalary(); Tax createTax(); }
package Create.c.AbstractFactory; //业务实现类工厂类 public class HeBeiFactory implements Factory { @Override public Salary createSalary() { // TODO Auto-generated method stub return new HeBeiSalary(); } @Override public Tax createTax() { // TODO Auto-generated method stub return new HeBeiTax(); } }
package Create.c.AbstractFactory; //业务实现类工厂类 public class GuangDongFactory implements Factory { @Override public Salary createSalary() { // TODO Auto-generated method stub return new GuangDongSalary(); } @Override public Tax createTax() { // TODO Auto-generated method stub return new GuangDongTax(); } }
package Create.c.AbstractFactory; //业务调用类 public class Client { public static void main(String[] args) { Factory fa = new GuangDongFactory(); Salary sa = fa.createSalary(); Tax tax = fa.createTax(); sa.calcSalary(); tax.calcTax(); fa = new HeBeiFactory(); sa = fa.createSalary(); tax =fa.createTax(); sa.calcSalary(); tax.calcTax(); } }
优点:所有实现类设计到一个工厂类里面,客户端调用变得非常简单,并且如果需要更换一个系列的产品,只需要更换一个工厂类即可
缺点:如果涉及需求变更或添加,则需要修改抽象工厂类,并同时修改实现这个抽象工厂类的具体实现类,添加额外编码的工作量(跟工厂方法模式相同)