码迷,mamicode.com
首页 > 其他好文 > 详细

大话设计模式----工厂方法模式

时间:2020-04-02 22:52:17      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:turn   设计模式   ace   大话设计模式   creat   对象   延迟   接口   print   

一、工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

二、代码示例

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();
    }
}

工厂方法模式是简单工厂模式的进一步抽象和推广。

大话设计模式----工厂方法模式

标签:turn   设计模式   ace   大话设计模式   creat   对象   延迟   接口   print   

原文地址:https://www.cnblogs.com/zsmcwp/p/12623360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!