工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
简单工厂模式违背了"开放-封闭"原则(再添加控制类时在简单工厂类中要修改),工厂方法模式在添加控制类时,再添加控制类对应的工厂,克服了简单工厂违背了"开放-封闭"原则。
Leifeng.java类
package factory; public class Leifeng { public void sweep(){ System.out.println("扫地"); } public void wash(){ System.out.println("洗衣"); } public void buyRice(){ System.out.println("买米"); } }
Undergraduate.java类
package factory; public class Undergraduate extends Leifeng { }
Volunteer.java类
package factory; public class Volunteer extends Leifeng { }
IFacory.java类
package factory; public abstract class IFacory { public abstract Leifeng createLeifeng(); }
UndergraduateFactory.java类
package factory; public class UndergraduateFactory extends IFacory { @Override public Leifeng createLeifeng() { Leifeng lf = new Leifeng(); return lf; } }
VolunteerFactory.java类
package factory; public class VolunteerFactory extends IFacory { @Override public Leifeng createLeifeng() { Leifeng lf = new Volunteer(); return lf; } }
Business.java类
package factory; public class Business { public static void main(String[] args) { IFacory factory = new UndergraduateFactory(); Leifeng lf1 = factory.createLeifeng(); Leifeng lf2 = factory.createLeifeng(); Leifeng lf3 = factory.createLeifeng(); lf1.buyRice(); lf2.sweep(); lf3.wash(); IFacory vfactory = new VolunteerFactory(); Leifeng vl1 = vfactory.createLeifeng(); Leifeng vl2 = vfactory.createLeifeng(); Leifeng vl3 = vfactory.createLeifeng(); vl1.buyRice(); vl2.wash(); vl3.sweep(); } }