工厂方法模式与简单工厂模式的主要区别在于:工厂方法模式将简单工厂模式的工厂类抽象为一个父类,然后有多个子类的生成工厂
一、编写一个学雷锋做好事程序
雷锋父类:
public class LeiFeng {
public void sweep() {
System.out.println("扫地");
}
public void boilingWater() {
System.out.println("烧水");
}
}
学生雷锋子类:
public class Student extends LeiFeng{
@Override
public void sweep() {
System.out.println("学生扫地");
}
@Override
public void boilingWater() {
System.out.println("学生烧水");
}
}
志愿者雷锋子类:
public class Volunteer extends LeiFeng{
@Override
public void sweep() {
System.out.println("志愿者扫地");
}
@Override
public void boilingWater() {
System.out.println("志愿者烧水");
}
}
工厂抽象父类:
public abstract class FactoryCreate {
public abstract LeiFeng create();
}
学生工厂子类:
public class StudentFactory extends FactoryCreate{
@Override
public LeiFeng create() {
return new Student();
}
}
志愿者工厂子类:
public class VolunteerFactory extends FactoryCreate{
@Override
public LeiFeng create() {
return new Volunteer();
}
}
测试类:
public class Test {
public static void main(String[] args) {
FactoryCreate factoryCreate=new StudentFactory();
LeiFeng leiFeng=factoryCreate.create();
leiFeng.boilingWater();
leiFeng.sweep();
factoryCreate=new VolunteerFactory();
leiFeng=factoryCreate.create();
leiFeng.boilingWater();
leiFeng.sweep();
}
}
输出结果:
工厂方法模式遵守了开放-封闭原则(对修改是封闭的,对扩展是开放的),将类的实例化延迟到了子类