工厂方法模式--结合具体例子学习工厂方法模式

在学习工厂方法模式之前,可以先学习一下简单工厂模式,网址是http://blog.csdn.net/u012116457/article/details/21650421,这里仍以水果的实例讲解。

 

先来说说简单工厂模式的特点,简单工厂模式将具体类的创建交给了工厂,使客户端不再直接依赖于产品,但是其违背了OCP原则,当对系统进行扩展时,仍然需要去修改原有的工厂类的代码。

而工厂方法模式则解决了这一问题,在工厂方法模式中,核心工厂类不再负责产品的创建,而把其延迟到其子类当中,核心工厂类仅仅为其子类提供必要的接口。

现在,结合下面的例子具体的理解一下工厂方法模式:

interface Fruit{
	public String tell();
}
interface Factory{
	public Fruit getFruit();
} 

//苹果类
class Apple implements Fruit{
	public String tell(){
		return "我是苹果";
	}
}
//香蕉类
class Banana implements Fruit{
	public String tell(){
		return "我是香蕉";
	}
} 
class AppleFactory implements Factory{
	public Fruit getFruit(){
		return new Apple();
	}
}
class BananaFactory implements Factory{
	public Fruit getFruit(){
		return new Banana();
	}
}
public class Store {
	public static void main(String[] args) {
       Fruit f= null; 
       Factory factory = null;
       
       factory=new AppleFactory();  
       f=  factory.getFruit();   
       System.out.println( f.tell());   
       
       factory=new BananaFactory();  
       f=factory.getFruit();  
       System.out.println( f.tell());	}
}


 

定义一个工厂接口,让具体的工厂类去实现它,从代码中不难看出,当对代码进行扩展时,比如要加入一个Grape类,只需要定义一个Grape类,并定义一个Grape的工厂类GrapeFactory去继承工厂接口即可,而不必对原有的代码进行修改,完全符合OCP原则

posted @ 2014-03-22 00:00  IT专业户  阅读(177)  评论(0编辑  收藏  举报