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

工厂模式

时间:2016-05-29 22:45:56      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

public interface Factory {
    public LeiFeng CreateLeiFeng();
}
public class LeiFeng {
    public void sweep() {
        System.out.println("sweep");
    }

    public void wash() {
        System.out.println("wash");
    }

    public void buyRice() {
        System.out.println("buy rice");
    }
}
/**
 * Created by tian on 16-5-29.
 * <p>
 * 定义一个用于创建对象的接口,让子类决定实例化哪一个对象。工厂方法使一个类的实例化延迟到其子类
 * 工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,
 * 也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。想要增加新功能,原来是修改工厂类,
 * 现在是修改客户端。
 */
public class Main {
    public static void main(String[] args) {
        //简单工厂模式
        LeiFeng studentA = SimpleFactory.CreateLeiFeng("xuesehng");
        LeiFeng zhiyuanzhe = SimpleFactory.CreateLeiFeng("zhiyuanzhe");
        //工厂模式
        Factory factory = new UnderGraduateFactory();
        LeiFeng xuesheng = factory.CreateLeiFeng();
    }
}
/**
 * Created by tian on 16-5-29.
 * //简单工厂的实现方法
 */
public class SimpleFactory {
    public static LeiFeng CreateLeiFeng(String type){
        LeiFeng leiFeng = null;
        switch (type){
            case "xuesheng":
                leiFeng = new UnderGraduate();
                break;
            case "zhiyuanzhe":
                leiFeng = new Volunteer();
        }
        return leiFeng;
    }
}
public class UnderGraduate extends LeiFeng{

}
public class UnderGraduateFactory implements Factory {
    @Override
    public LeiFeng CreateLeiFeng() {
        return new UnderGraduate();
    }
}
public class Volunteer extends LeiFeng {
}
public class VolunterFactory implements Factory{

    @Override
    public LeiFeng CreateLeiFeng() {
        return new Volunteer();
    }
}

 

工厂模式

标签:

原文地址:http://www.cnblogs.com/benniaoxuefei/p/5540496.html

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