**工厂方法模式:**定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
简单工厂模式的最大优点在于工厂类种包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
如上面的·计算器案例如果再增加一个运算方法在case分支条件修改原有的类,违背了开放封闭原则,不但对扩展进行了开放也对修改进行了开放。
public interface IFactory { LeiFeng CreateLeiFeng();}
public class LeiFeng { public void Sweep(){ System.out.println("扫地"); } public void Wash(){ System.out.println("洗衣"); } public void BuyRice(){ System.out.println("买米"); }}``````javapublic class Volunteer extends LeiFeng{}
public class Undergraduate extends LeiFeng{}
public class UndergraduateFactory implements IFactory { @Override public LeiFeng CreateLeiFeng() { return new Undergraduate(); } public UndergraduateFactory() { System.out.println("大学生工厂"); }}
public class VolunteerFactory implements IFactory { @Override public LeiFeng CreateLeiFeng() { return new Volunteer(); } public VolunteerFactory() { System.out.println("志愿者工厂"); }}
public class Client { public static void main(String[] args) { IFactory factory=new UndergraduateFactory(); LeiFeng student=factory.CreateLeiFeng(); student.BuyRice(); student.Sweep(); student.Wash(); }}