一、工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
二、代码示例
public class LeiFeng { public void seep() { System.out.println("扫地"); } public void wash() { System.out.println("洗衣"); } public void buyRice() { System.out.println("买大米"); } } public class Undergraduate extends LeiFeng { } public class Volunteer extends LeiFeng { } public interface IFactory { LeiFeng createLeiFeng(); } public class UndergraduateFactory implements IFactory { @Override public LeiFeng createLeiFeng() { System.out.println("======Undergraduate======="); return new Undergraduate(); } } public class VolunteerFactory implements IFactory { @Override public LeiFeng createLeiFeng() { System.out.println("======Volunteer======="); return new Volunteer(); } } public class Test { public static void main(String[] args) { // IFactory iFactory = new UndergraduateFactory(); IFactory iFactory = new VolunteerFactory(); LeiFeng leiFeng = iFactory.createLeiFeng(); leiFeng.buyRice(); leiFeng.seep(); leiFeng.wash(); } }
工厂方法模式是简单工厂模式的进一步抽象和推广。
原文地址:https://www.cnblogs.com/zsmcwp/p/12623360.html
时间: 2024-10-11 16:42:10