Chapter 8 工厂方法模式

工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。你想要加功能,本来是改工厂类的,而现在是修改客户端。

代码如下:

package xiao;

class LeiFeng{
public void sweep(){
System.out.println("sweep!");
}
public void wash(){
System.out.println("wash!");
}
public void buyRice(){
System.out.println("buyRice!");
}
}
class Undergraduate extends LeiFeng{

}
interface IFactory{
public LeiFeng createLF();
}
class UndergraduateFactory implements IFactory{
public LeiFeng createLF(){
return new Undergraduate();
}
}
class Volunteer extends LeiFeng{

}
class VolunteerFactory implements IFactory{
public LeiFeng createLF(){
return new Volunteer();
}
}
public class Hello {

public static void main(String[] args) throws Exception{
IFactory factory = new UndergraduateFactory();
LeiFeng student = factory.createLF();
student.buyRice();
student.sweep();
student.wash();
}
}

工厂方法克服了简单工厂违背开放-封闭原则的缺点,又保持了封装对象创建过程的优点。

posted on 2014-05-17 10:27  颓废的悠然  阅读(186)  评论(0编辑  收藏  举报

导航