package Create.a.SimpleFactory;
//业务接口 public interface Salary { void calcSalary(); }
package Create.a.SimpleFactory;
//业务实现类 public class HeBeiSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算河北子公司的薪资!"); } }
package Create.a.SimpleFactory; //业务实现类 public class GuangDongSalary implements Salary { @Override public void calcSalary() { // TODO Auto-generated method stub System.out.println("开始计算广东子公司的薪资!"); } }
package Create.a.SimpleFactory; //工厂类 public class SimpleFactory { public static Salary createSalary(String name){ if(name.equals("HeBei")){ return new HeBeiSalary(); } if(name.equals("GD")){ return new GuangDongSalary(); } return null; } } 如果后期需求需要变更时,即需要变动if条件内容
package Create.a.SimpleFactory; //业务调用类 public class Client { public static void main(String[] args) { Salary sa = SimpleFactory.createSalary("HeBei"); sa.calcSalary(); sa = SimpleFactory.createSalary("GD"); sa.calcSalary(); } }
优点:在简单工厂模式中,客户端不再负责对象的创建,而是把这个任务丢给工厂类,客户端只负责对对象实例的调用
缺点:无法继承,变更需求时需要不断修改工厂类的判断逻辑