java开源文档大全致力于打造中国最大最全的开源文档,它提供了最全面最权威的开源资料,同时为大家提供一个交流的平台,如果您有好的想法,欢迎您投稿.
先说Factory Method 和 Template Method,它们经常会一起被使用,原先对这两个模式的区别比较模糊:Factory Method 是一个抽象方法,具体实现在子类;而 Template Method 里也有些抽象方法,具体实现在子类;那他们之间什么区别?是由于看书不仔细,概念没理解。 我们可以这样简单的认为:这些抽象的方法称之为 Factory Method,即定义在超类实现在子类的方法; Template Method 也是一个方法,它里面定义了一个算法逻辑,而这个算法逻辑可能要调用许多别的方法实现,这些‘别的方法’里就可能包含 Factory Method. 例子:
代码 再对照看它们各自的定义,就更好理解了。 Factory Method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Template Method里所说的’lets subclasses redefine certain steps’就可以使用Factory Method. 在GOF书的Template Method 那章里是这样概述这两个模式之间关系的: Factory Methods are often called by template methods. 再就是Strategy Pattern,Spring Framework 里的DI就使用了这个模式。 修改了下上面的例子:
代码 代码 代码 代码 PizzaCreator 接口定义了一个行为createPizza,具体实现类体现了不同的实现细节,比如londonPizzaCreator和nYorkPizzaCreator’生产’的Pizza肯定不一样。再通过给PizzaStore 设置(setPizzaCreator)不同的PizzaCreator 获得不同的Pizza(Pizza pizza = pizzaCreator.createPizza(type);)。 londonPizzaCreator和nYorkPizzaCreator就体现了Strategy Pattern,它们对createPizza有各自的实现算法,而使用时不需要知道其实现细节。它和Template Method的区别在于Strategy实现了算法逻辑,而Template Method只定义了算法的’框架’,而其中有些具体实现会涉及到子类。 Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Related to Template Method: Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm. // ------------------------------------------------------------ 一点学习体会,有不对的地方望大家指点。
java开源文档研究struts,webwork,spring,tomcat,jboss,lucense,nutch,JUnit,eclipse......,如果您有什么意见,欢迎评论和留言. |