Abstract Comparing the Template Method and Strategy Design Patterns in a Genetic Algorithm

合集下载

深入浅出设计模式之模板方法模式

深入浅出设计模式之模板方法模式

深入浅出设计模式之模板方法模式模板方法模式(Template Method Pattern)是一种行为型设计模式,它定义了一个操作中的算法的骨架,将一些步骤的具体实现延迟到子类中。

模板方法模式使得子类可以在不改变算法结构的情况下重新定义算法中的一些步骤。

模板方法模式主要由两个主要角色组成:抽象类和具体类。

抽象类定义了一个模板方法,该方法中包含了算法的主要结构,这些方法可以是具体方法、抽象方法或钩子方法。

具体类实现了抽象类中的抽象方法,并且可以通过重写这些方法来调整算法的具体实现。

模板方法模式的核心思想是将不变的部分封装在父类中,将可变的部分延迟到子类中实现。

这样可以避免代码重复,提高代码的复用性。

模板方法模式还可以通过钩子方法来控制算法的执行流程,以便在特定情况下改变算法的行为。

使用模板方法模式可以优化代码的结构,使得算法的变化对客户端来说是透明的。

在设计框架的时候,我们可以在抽象类中定义模板方法,然后在具体类中根据实际需求重写这个方法,从而实现对框架的定制。

下面以一个烹饪例子来说明模板方法模式的应用:假设我们要设计一个烹饪类,该类可以用于制作多个菜品,其中有些菜品需要使用到火,有些菜品则不需要。

我们可以将烹饪过程抽象成一个模板方法,其中包括了一些步骤,例如准备食材、加热等。

首先,我们定义一个烹饪类Cooking,其中包含一个模板方法cook,用于定义烹饪的步骤:```public abstract class Cookingpublic final void cooprepareIngredients(;if (needHeat()heat(;}serve(;}protected abstract void prepareIngredients(; protected abstract void heat(;protected void servSystem.out.println("上菜");}protected boolean needHeareturn true;}```在烹饪类中,prepareIngredients和heat方法都是抽象方法,需要子类来实现。

抽象类作文英语模版

抽象类作文英语模版

抽象类作文英语模版英文回答:Introduction.In the realm of object-oriented programming, the concept of abstraction occupies a pivotal position. Abstraction allows us to encapsulate the essential characteristics and behaviors of real-world entities into classes, providing a structured and reusable blueprint for creating objects. Among the various class types, abstract classes hold a unique distinction, serving as a foundation for defining common interfaces and preventing the instantiation of incomplete or invalid objects.Definition of an Abstract Class.An abstract class is a class that cannot be instantiated directly but must be subclassed to create concrete objects. It serves as a template that defines theinterface and shared functionality of a group of related classes. By declaring at least one of its methods as abstract, an abstract class ensures that subclasses must implement the method with specific behavior before they can be used.Characteristics of Abstract Classes.1. Cannot be instantiated: Abstract classes cannot be used to create objects directly. They exist solely to provide a blueprint for subclasses to inherit and expand upon.2. Contain abstract methods: Abstract classes declare one or more abstract methods, which are method signatures without implementations. Subclasses must override these abstract methods with concrete implementations to provide specific functionality.3. May contain concrete methods: In addition to abstract methods, abstract classes can also include concrete methods, which provide default implementationsthat subclasses can inherit or override.4. Act as a contract: Abstract classes define a contract that subclasses must adhere to. By implementing the abstract methods, subclasses guarantee that they possess the required functionality and follow the established interface.Uses of Abstract Classes.Abstract classes offer various advantages, including:1. Enforce method signatures: They ensure that subclasses implement the required methods with the correct signatures, preventing inconsistencies and enforcing a common interface.2. Promote code reusability: By providing a shared interface, abstract classes facilitate code reusability across subclasses, reducing duplication and promoting maintainability.3. Prevent incomplete objects: By prohibiting direct instantiation, abstract classes prevent the creation of invalid or incomplete objects, ensuring that only objects with complete and consistent functionality are created.4. Promote polymorphism: Abstract classes support polymorphism, allowing objects of different subclasses to be treated as objects of the abstract class, fostering flexibility and extensibility in code.Example of an Abstract Class.Consider the following abstract class representing the concept of a shape:java.public abstract class Shape {。

java的abstract method

java的abstract method

Java的Abstract Method一、什么是Abstract Method在Java中,抽象方法(Abstract Method)是指在父类中声明但没有具体实现的方法。

抽象方法没有方法体,只有方法的声明,以关键字abstract修饰。

抽象方法的存在主要是为了让子类去实现,它相当于一种“约定”或“规范”,告诉子类必须实现这个方法。

二、抽象方法的特点和用途抽象方法具有以下特点:1.抽象方法必须声明在抽象类或接口中。

2.抽象方法没有方法体,以分号结尾。

3.抽象方法必须被子类实现,除非子类也是抽象类。

4.如果一个类继承了抽象类,那么它必须实现抽象类中的所有抽象方法,否则必须将自己也声明为抽象类。

抽象方法的主要用途是定义一种接口或协议,强制要求子类实现这个方法。

通过抽象方法,我们可以在父类中定义一些通用的行为,然后由不同的子类根据自己的特性来实现具体的细节。

这样可以提高代码的可扩展性和重用性。

三、抽象方法的语法定义抽象方法的语法如下:[访问修饰符] abstract返回类型方法名(参数列表);其中:•访问修饰符:可以是public、protected、private或默认修饰符。

•返回类型:表示方法的返回值类型,可以是任意合法的数据类型。

•方法名:表示方法的名称。

•参数列表:表示方法的参数,可以有零个或多个参数。

四、如何使用抽象方法使用抽象方法需要按照以下步骤进行:1.创建一个抽象类或接口,并在其中声明抽象方法。

2.在子类中实现抽象方法。

4.1 创建抽象类抽象类用关键字abstract修饰,可以包含抽象方法,也可以包含非抽象方法。

抽象类不能被实例化,只能被继承。

下面是一个抽象类的示例:public abstract class Animal {public abstract void makeSound();public void sleep() {System.out.println("Animal is sleeping");}}4.2 实现抽象方法在子类中,必须实现父类中的所有抽象方法,否则子类也必须声明为抽象类。

设计模式——15模板方法模式与访问者模式

设计模式——15模板方法模式与访问者模式

insertCard(); validateCard(); useATM(); popCard();
Withdraw
+ <<Override>> useATM () : void
ShowBalance
+ <<Override>> useATM () : void
Transfer
+ <<Override>> useATM () : void
ObjectStructure
Element
+ accept (Visitor v) : void
ConcreteElementA
+ accept (Visitor v) : void + operationA () : void
ConcreteElementB
+ accept (Visitor v) : void + operationB () : void
Apple
+ <<Implement>> accept (Visitor visitor) : void
Books
+ <<Implement>> accept (Visitor visitor) : void
访问者模式(续)
实例分析 实例一:购物车(代码实现)
访问者模式(续)
Client Visitor
实例分析 实例二:汽车访问模拟(代码实现)
访问者模式(续)
模式优缺点 访问者模式有如下的优点:
访问者模式使得增加新的操作变得很容易。如果一些操作依赖于一个复杂的结

abstract类中method

abstract类中method

abstract类中method⼀、abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?都不可以,因为abstract申明的⽅法是要求⼦类去实现的,abstract只是告诉你有这样⼀个接⼝,你要去实现,⾄于你的具体实现可以是native和synchronized,也可以不是,抽象⽅法是不关⼼这些事的,所以写这两个是没有意义的。

然后,static⽅法是不会被覆盖的,⽽abstract⽅法正是要⼦类去覆盖它,所以也是没有意义的。

所以,总的来说,就是Java语法不允许你这样做,事实上,也没有意义这样做。

abstract需要重载,static为类⽅法,没有重载⼀说 abstract为没有实现的⽅法,native为本机实现的⽅法,⾃相⽭盾 abstract⽅法没有实现,也不可能实际调⽤抽象⽅法,没有必要synchronized修饰,当然⼦类可以根据需要同步该⽅法.所以都不能.⼆,接⼝是否可继承接⼝? 抽象类是否可实现(implements)接⼝? 抽象类是否可继承实体类(concrete class)? 接⼝可以继承接⼝。

抽象类可以实现(implements)接⼝,抽象类是否可继承实体类,但前提是实体类必须有明确的构造函数。

三,启动⼀个线程是⽤run()还是start()? 启动⼀个线程是调⽤start()⽅法,使线程所代表的虚拟处理机处于可运⾏状态,这意味着它可以由JVM调度并执⾏。

这并不意味着线程就会⽴即运⾏。

run()⽅法可以产⽣必须退出的标志来停⽌⼀个线程。

四,构造器Constructor是否可被override? 构造器Constructor不能被继承,因此不能重写Overriding,但可以被重载Overloading。

Template Method模式在Android中的应用

Template Method模式在Android中的应用

Template Method模式在Android中的应用Template Method模式是一种行为设计模式,它可以帮助我们在一个类中定义算法的框架,同时留出一些步骤的具体实现由子类来完成。

这个模式的核心思想是“定义好骨架,留出具体实现的空间”。

在Android开发中,我们能够发现许多地方都可以使用Template Method模式。

比如我们在写Activity时,通常都需要覆写onCreate()和onDestroy()等生命周期方法,并在其中做一些初始化和回收工作。

这个时候,我们就可以使用Template Method模式,把onCreate()和onDestroy()等生命周期方法定义到一个基类中,并留出一些步骤的具体实现由子类来完成。

下面,我们来详细探讨一下如何在Android中使用Template Method模式。

1. 定义一个基类首先我们需要定义一个基类,比如我们可以定义一个叫做BaseActivity的类,用来作为所有Activity的基类。

在BaseActivity中,我们可以定义onCreate()和onDestroy()等生命周期方法的框架,同时留出一些抽象方法,由子类来实现具体细节。

```public abstract class BaseActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(getLayoutId());initView();initData();initEvent();}protected abstract int getLayoutId();protected abstract void initView();protected abstract void initData();protected abstract void initEvent();@Overrideprotected void onDestroy() {super.onDestroy();doDestroy();}protected abstract void doDestroy();}```在BaseActivity中,我们定义了onCreate()和onDestroy()等生命周期方法的框架,同时留出了四个抽象方法getLayoutId()、initView()、initData()和initEvent(),它们的具体实现由子类来完成。

template method 设计模式

template method 设计模式

Template Method(模板方法)是一种行为型设计模式,它定义了一个算法的骨架,而将一些步骤的实现延迟到子类。

这种设计模式允许子类在不改变算法结构的情况下重新定义算法的部分步骤。

二、背景在软件开发中,经常会遇到需要定义一个算法的骨架,而将一些步骤的具体实现留给子类的情况。

一个操作中的步骤顺序一般是固定的,但是其中的某些步骤可能会有所不同,这时就可以使用Template Method设计模式来实现。

三、组成Template Method设计模式由两部分组成:抽象父类和具体子类。

抽象父类定义了算法的骨架,其中包含一个模板方法和若干个基本方法。

模板方法用于定义算法的结构,基本方法用于实现算法的具体步骤。

具体子类继承抽象父类,并实现基本方法,以完成算法的具体实现。

四、实现方式Template Method设计模式的实现方式如下:1. 创建一个抽象父类,其中包含一个模板方法和若干个基本方法。

模板方法用于定义算法的结构,而基本方法用于实现算法的具体步骤。

抽象父类的模板方法中的步骤顺序是固定的,而具体实现可由子类来2. 创建具体子类,继承抽象父类,并实现基本方法。

具体子类中的基本方法用于完成算法的具体实现。

3. 客户端通过调用抽象父类的模板方法来使用算法,具体的实现将由子类来完成。

五、示例以下是一个使用Template Method设计模式的示例:```javapublic abstract class AbstractClass {public void templateMethod() {System.out.println("Step 1");step2();System.out.println("Step 3");step4();}public abstract void step2();public abstract void step4();}public class ConcreteClass1 extends AbstractClass {public void step2() {System.out.println("ConcreteClass1 Step 2");}public void step4() {System.out.println("ConcreteClass1 Step 4");}}public class ConcreteClass2 extends AbstractClass {public void step2() {System.out.println("ConcreteClass2 Step 2");}public void step4() {System.out.println("ConcreteClass2 Step 4");}}public class Client {public static void m本人n(String[] args) {AbstractClass abstractClass1 = new ConcreteClass1(); abstractClass1.templateMethod();AbstractClass abstractClass2 = new ConcreteClass2(); abstractClass2.templateMethod();}}```在上面的示例中,AbstractClass定义了一个模板方法templateMethod,其中包含了Step 1、Step 3两个固定的步骤,并将Step 2、Step 4的实现留给子类来完成。

模板匹配算法 肋骨

模板匹配算法 肋骨

模板匹配算法肋骨Template matching algorithm is a technique used in computer vision to find a template image within a larger image. This involves comparing the template image with different sub-regions of the larger image to determine where the template image appears. 模板匹配算法是计算机视觉中一种用于在较大图像中查找模板图像的技术。

这涉及将模板图像与较大图像的不同子区域进行比较,以确定模板图像出现在何处。

The key concept behind template matching is to find the best match between the template image and the larger image. This is done by calculating a similarity measure, such as the sum of squared differences or cross-correlation, between the template and the sub-regions of the larger image. 模板匹配的关键概念是找到模板图像和较大图像之间的最佳匹配。

这是通过计算相似度度量(如平方差的和或交叉相关)在模板图像和大图像的子区域之间完成的。

One of the challenges of template matching is dealing with variations in scale, rotation, and lighting conditions between the template and the larger image. This can affect the accuracy of the matching process and lead to false positives or false negatives. 模板匹配面临的挑战之一是处理模板图像与较大图像之间的尺度、旋转和光照条件变化。

java 实现模板方法

java 实现模板方法

java 实现模板方法模板方法定义在抽象类中,它在一个或多个步骤中定义了一个算法的骨架,将一些步骤延迟到子类中实现。

模板方法允许子类在不改变算法结构的情况下重定义算法的某些步骤。

以下是一个简单的Java模板方法示例:```javapublic abstract class AbstractClass {// 模板方法public final void templateMethod() {step1();step2();step3();}// 具体方法1protected abstract void step1();// 具体方法2protected abstract void step2();// 具体方法3protected abstract void step3();}```在这个例子中,`AbstractClass`是一个抽象类,其中包含一个模板方法`templateMethod`,该方法执行三个步骤(`step1`,`step2`,和`step3`)。

这些步骤被声明为抽象方法,这意味着子类必须提供这些方法的具体实现。

下面是一个实现这个抽象类的子类:```javapublic class ConcreteClass extends AbstractClass {Overrideprotected void step1() {("执行步骤1");}Overrideprotected void step2() {("执行步骤2");}Overrideprotected void step3() {("执行步骤3");}}```在这个子类中,我们提供了`step1`,`step2`和`step3`的具体实现。

当我们创建一个`ConcreteClass`的实例并调用`templateMethod`时,它将按照我们在`AbstractClass`中定义的顺序执行这些步骤。

苍盾考研英语作文模板咋样

苍盾考研英语作文模板咋样

As a high school student preparing for the college entrance examination, Ive always been intrigued by the strategies and tools that can help me excel in English, especially when it comes to writing. One such resource that has caught my attention is the Cangdun Postgraduate English Composition Template. While I havent personally used it, Ive heard about its effectiveness from my peers and teachers, and Id like to share some insights based on what Ive gathered.The Cangdun Postgraduate English Composition Template is designed to assist students in structuring their essays effectively, particularly for postgraduate entrance exams. Its a set of guidelines that can help students organize their thoughts and present them in a coherent and persuasive manner. Heres a breakdown of what makes this template stand out:1. Clear Structure: The template provides a clear and logical structure for essay writing. It starts with an introduction that grabs the readers attention, followed by body paragraphs that present the main points, and concludes with a summary that reinforces the argument.2. Cohesive Flow: One of the key features of the template is its emphasis on the flow of ideas. It encourages students to use transitional phrases and sentences that connect the different parts of the essay, making it easier for readers to follow the argument.3. Vocabulary Enhancement: The template includes a variety of advanced vocabulary and idiomatic expressions that can elevate the language of the essay. This not only impresses the examiners but also demonstrates thestudents command of the English language.4. Argument Development: It guides students on how to develop a strong argument. This includes presenting evidence, analyzing different viewpoints, and providing counterarguments where necessary.5. Practice Makes Perfect: The template is not just about theory it encourages students to practice writing essays using the template. This practice helps students internalize the structure and improve their writing skills over time.6. Customization: While the template provides a general framework, it also allows for customization. Students can adapt the template to fit the specific requirements of different essay topics and types.7. Time Management: For exams, time is of the essence. The template helps students manage their time effectively by providing a clear roadmap for essay writing, ensuring that they can complete their essays within the allotted time.8. Feedback and Revision: Using the template also facilitates the process of selfassessment and revision. By comparing their essays against the template, students can identify areas for improvement and refine their writing.In conclusion, the Cangdun Postgraduate English Composition Template seems to be a valuable tool for students aiming to excel in Englishcomposition, particularly for those preparing for competitive exams. It offers a comprehensive approach to essay writing that focuses on structure, language, and argument development. While I have yet to use it myself, Im considering incorporating it into my study routine to enhance my writing skills and prepare for the challenges ahead.。

sacrificial template method

sacrificial template method

sacrificial template methodSacrificial Template Method(牺牲模板方法)是一种在软件开发中常用的设计模式。

这个模式是由Gang of Four中的四位软件开发专家提出的,在大多数实例中,它用于编写框架,特别是基于框架的应用程序。

在这篇文章中,我们将介绍Sacrificial Template Method的定义,如何应用和其优点。

一、定义Sacrificial Template Method是一种以新建、循环和结束步骤为基础的设计模式。

在该模式中,父类(模板类)定义一个模板方法,其中固定了算法的基本架构,但是允许子类通过扩展某些步骤以适应特定的场景。

模板方法允许子类重写关键步骤,这使得每个子类都能够以自己独特的方式处理代码。

换句话说,该模式允许开发人员在一些步骤上进行动态调整,而不会破坏算法的整体结构。

二、应用下面是几种常见的应用情况:1. 处理框架Sacrificial Template Method是设计框架的常用方法之一。

在这种情况下,开发人员定义了一组类和方法,并使用Sacrificial Template Method来对自定义代码进行适应。

2. 处理大型体系结构大型体系结构往往包含多个抽象层次。

使用Sacrificial Template Method时,开发人员可以为每个层设置一个抽象方法。

任务将移交给子类以完成。

3. 处理并发或分布式设计在分布式或全球范围内操作的系统中,Sacrificial Template Method可用于控制并行操作的工作流程。

三、优点使用Sacrificial Template Method的优点在于它提供了一个始终如一的架构。

此外,这种方法可以使多个子类从共同的父类中继承代码,并允许以不同的方式处理模板中的步骤。

另一个优点是,在Sacrificial Template Method 中,使用继承的优势可以为代码分类,而不是硬编码依赖。

英语比较作文模板

英语比较作文模板

英语比较作文模板Comparative Essay Template。

Introduction:In today's world, we are constantly making comparisons. Whether it's comparing products, services, or even people, we are always trying to determine which is better. In this essay, I will compare and contrast two different subjectsin order to highlight their similarities and differences. Body Paragraph 1:The first subject I will compare is [subject A]. This subject is known for [describe characteristics]. On the other hand, [subject B] is known for [describe characteristics]. While both subjects have their own unique qualities, there are also some similarities between them. For example, both [subject A] and [subject B] are [similar characteristic].Body Paragraph 2:The second subject I will compare is [subject B]. As previously mentioned, [subject B] is known for [describe characteristics]. In contrast, [subject A] is known for [describe characteristics]. Despite their differences, there are still some similarities between the two subjects. For instance, both [subject B] and [subject A] are [similar characteristic].Body Paragraph 3:Now let's take a closer look at the differences between [subject A] and [subject B]. One major difference between the two is [difference 1]. Another difference is [difference 2]. While these differences may seem significant, they do not necessarily make one subjectbetter than the other.Conclusion:In conclusion, while [subject A] and [subject B] have their own unique characteristics and differences, they also share some similarities. It's important to recognize that both subjects have their own strengths and weaknesses and that one is not necessarily better than the other. By comparing and contrasting these two subjects, we can gain a better understanding of their similarities and differences and appreciate them for what they are.。

Java设计模式之模板方法模式(Template)

Java设计模式之模板方法模式(Template)

Java设计模式之模板⽅法模式(Template)前⾔: 我们在开发中有很多固定的流程,这些流程有很多步凑是固定的,⽐如JDBC中获取连接,关闭连接这些流程是固定不变的,变动的只有设置参数,解析结果集这些是根据不同的实体对象“来做调整”,针对这种拥有固定算法流程,其中有固定的步凑,存在不固定的步凑的情况下就诞⽣了模板⽅法模式。

模板⽅法模式(Template)定义: 模板⽅法模式⼜叫模板模式,指的是⽗类定义了⼀个多步凑的算法⾻架,其中很多步凑是在⽗类中实现了的,有的步凑是根据不同的⼦类拥有不同的实现,就把这些“不确定”的实现步凑定义为抽象⽅法交给⼦类去实现。

模板模式的核⼼就是在使⼦类不改变算法结构的情况下,重新定义算法的某些步凑。

属于⾏为型设计模式。

应⽤很⼴发,⽐如Mybatis中的BaseExecutor;Spring中的JdbcTemplate;Spring集成Hibernate中的HibernateTemplate,Spring集成各种Mq的Template,还有MongodbTemplate等......模式中的⾓⾊: 抽象类(AbstractClass):实现了模板⽅法,定义了算法的⾻架。

具体类(Concrete):实现了抽象类中抽象放,使得⽗类定义的算法更完整。

代码实现: 1:⽤抽象类定义流程,⽐如我们每天上班有个流程:开机-->写代码(不同的程序员可能写不同的代码-->关机;整个流程中开机和关机是相同的,只是写代码这个步凑不同,java程序员写java代码,Php程序员写Php代码;我们先⽤⼀个抽象的⽗类定义这个流程:public abstract class Work {//定义算法步凑流程public void workDay(){//1:上班开机openComputer();//2:搬砖:写代码coding();//3:下班关机 closeComputer();}//开机private final void openComputer() {System.out.println("到达公司,开机");}//写代码protected abstract void coding();//关机private final void closeComputer() {System.out.println("下班,关机");}} 2:具体实现 Java程序员public class JavaProgrammer extends Work {@Overrideprotected void coding() {System.out.println("Java程序员打开Idea,写Java代码。

TemplateMethod模式(李建忠老师)

TemplateMethod模式(李建忠老师)

TemplateMethod模式(李建忠⽼师)Template Method设计模式主要运⽤的是虚函数的⼀些思想,因此我们可以通过这个模式对虚函数的有⼀个更深刻的认识,⾸先我们需要了解Template Method 模式它解决的是哪⼀类的问题:定义⼀个操作中算法的⾻架,⽽将⼀些步骤(虚函数)延迟到⼦类中去实现,Template Method模式使得⼦类可以不改变⼀个算法的结构即可重定义该算法的某些特定步骤。

⾸先我们来提出⼀个问题:我们需要开发⼀个程序,程序库(Library)开发⼈员开发1、3、5三个步骤,应⽤程序(Application)开发⼈员开发2、4两个步骤,然后将五个步骤连接起来⾸先来看⼀下在Template Method模式没有出现之前我们应该怎么去做,我们采⽤的是结构化流程,下⾯我贴出代码:class Library{public void step1(){Console.WriteLine("Library.step1");}public void step3(){Console.WriteLine("Library.step3");}public void step5(){Console.WriteLine("Library.step5");}}class Application{public bool step2(){Console.WriteLine("Application.step2");return true;}public void step4(){Console.WriteLine("Application.step4");}}class Program{public static void Main(){//虚拟流程的定义Library lib = new Library();Application app = new Application();lib.step1();if (app.step2()){lib.step3();}for (int i = 0; i < 3; i++){app.step4();}lib.step5();Console.ReadLine();}}前⾯我们说过,要将五个步骤连接起来,这⾥我们在Program类中定义了⼀个虚拟的流程将,这是我们要特别注意,流程的定义是在Program中,按我的理解,这就是⼀种结构化的编程。

模板方法模式(TemplateMethod)及应用

模板方法模式(TemplateMethod)及应用

模板⽅法模式(TemplateMethod)及应⽤模板⽅法模式定义了⼀个算法的步骤,并允许⼦类别为⼀个或多个步骤提供其实践⽅式。

让⼦类别在不改变算法架构的情况下,重新定义算法中的某些步骤。

(来⾃百度百科) 模板⽅法模式在框架中经常使⽤,了解此模式对于阅读框架源码⼗分有⽤。

我先描述⽣活中的实际场景,引申出模板⽅式模式,然后分析此模式在JDK中的使⽤,最后分析在框架SpringMVC中的使⽤。

1、冲咖啡和泡奶茶如何抽取成⼀个模板1.1 模板思路冲咖啡步骤(1)把⽔煮沸(2)把沸⽔冲咖啡(3)倒进杯⼦⾥(4)加奶加糖泡奶茶步骤(1)把⽔煮沸(2)把沸⽔泡茶叶(3)倒进杯⼦⾥(4)加点奶 可以发现,冲咖啡和泡奶茶有两个步骤是⼀样的:把⽔煮沸和倒⼊杯⼦中,有两个步骤不⼀样。

那么是不是将两个相同的⽅法抽取在⽗类当中,⽤final修饰,让咖啡和奶茶两个⼦类去继承这个⽗类,两个⼦类就具有了⽗类把⽔煮沸和倒⼊杯⼦中的能⼒。

再去分别实现另外两个步骤就可以了,最后完成冲咖啡和泡奶茶的流程。

可是,这种做法对于⽗类来说,整个步骤是不可控的,虽然⼦类具有了⽗类的⽅法,但是采⽤了怎样的步骤顺序去制作咖啡和奶茶,⽗类完全不清楚。

所以,这⾥要做出⼀些改进,如果我们能在⽗类中将咖啡或者奶茶的每⼀个步骤都定义好,需要⼦类实现的⽅法定义成抽象类,然后将整个流程封装在⼀个⽅法⾥,⼦类继承⽗类后直接调⽤⽗类的这个⽅法,就能完全控制住整个操作步骤了。

1.2 具体的代码实现/*** 茶和咖啡的抽象⽗类*/public abstract class CaffeineBeverage {public final void prepareRecipe(){boilWater();brew();pourCup();addCondiment();}abstract void brew();abstract void addCondiment();void boilWater(){System.out.println("烧⽔");}final void pourCup(){System.out.println("倒⼊杯⼦中");}}public class Coffee extends CaffeineBeverage {@Overridevoid brew() {System.out.println("加⼊咖啡");}@Overridevoid addCondiment() {System.out.println("加⼊奶泡和糖");}}public class Tea extends CaffeineBeverage {@Overridevoid brew() {System.out.println("放⼊茶叶");}@Overridevoid addCondiment() {System.out.println("加点奶");}}public class TemplateMethodPattern {public static void main(String[] args) {Coffee coffee = new Coffee();coffee.prepareRecipe();}}1.3 代码分析 使⽤了模板⽅法,⼦类只需要去继承⽗类并实现⽗类中的抽象⽅法,但具体的执⾏步骤还是在⽗类CaffeineBeverage中定义并⽤final修饰的,这⼀点保证了步骤的统⼀。

Java之模板方法模式(TemplateMethod)

Java之模板方法模式(TemplateMethod)

Java之模板⽅法模式(TemplateMethod)1. 概念:定义⼀个算法的⾻架,⽽将⼀些实现步骤延迟到⼦类中。

把不变的⾏为搬到超类,去除⼦类中重复的代码来体现他的优势。

2. UML图:3.代码:public abstract class Templete{private void beforeOperation(){System.out.println("This acton before the operation!");}private void afterOperation(){System.out.println("This acton after the operation!");}//需要推迟到⼦类(实现类) 中执⾏protected abstract void operation();public void topOperation(){beforeOperation();operation();afterOperation();}}public class TempleteImpl extends Templete{protected void operation(){System.out.println("The operation action is executed in the method of ServiceA instance! ");}}public class TempletTest{public static void main(String[] args){Templete templete = new TempleteImpl();templete.topOperation();}}4.应⽤场景:1) ⼀次性实现⼀个算法的不变的部分,并将可变的⾏为留给⼦类来实现。

2) 各⼦类中公共的⾏为应被提取出来并集中到⼀个公共⽗类中以避免代码重复。

抽象类的模板方法设计模式

抽象类的模板方法设计模式

抽象类的模板⽅法设计模式⼀、前⾔:抽象类体现的就是⼀种模板模式的设计,抽象类作为多个⼦类的通⽤模板,⼦类在抽象类的基础上进⾏扩展、改造,但⼦类总体上会保留抽象类的⾏为⽅式。

⼆、模板⽅法能解决的问题:1、当功能内部⼀部分实现是确定的,⼀部分实现是不确定的。

这时可以把不确定的部分暴露出去,让⼦类去实现。

2、编写⼀个抽象⽗类,⽗类提供了多个⼦类的通⽤⽅法,并把⼀个或多个⽅法留给⼦类实现,就是⼀种模板模式。

三、代码实例://抽象类public abstract class Template {abstract void code();//要么就声明为实体⽅法,提供⽅法;要么就加上abstract关键字,声明为抽象⽅法public void spendTime(){long start=System.currentTimeMillis();this.code();//调⽤抽象⽅法long end=System.currentTimeMillis();System.out.println("程序运⾏的时间为:"+(end-start));}}//列出1-10000之间的素数class SubTemplate extends Template{public void code(){boolean flag=false;//⽤于判断是否为素数(只有1和本⾝)for(int i=2;i<=10000;i++){for(int j=2;j<=Math.sqrt(i);j++){if(i%j==0){//能够将2除尽,不是⼀个素数flag=true;break;}}if(!flag){//是⼀个素数,将其进⾏输出System.out.println(i);}flag=false;}}}class Test{public static void main(String[] args) {new SubTemplate().spendTime();//⼦类并没有对SubTemplate()进⾏重写,所以spendTime()仍为⽗类的⽅法}}。

JAVA模板方法模式

JAVA模板方法模式

JAVA模板⽅法模式模板⽅法模式的结构 模板⽅法模式是所有模式中最为常见的⼏个模式之⼀,是基于继承的代码复⽤的基本技术。

模板⽅法模式需要开发抽象类和具体⼦类的设计师之间的协作。

⼀个设计师负责给出⼀个算法的轮廓和⾻架,另⼀些设计师则负责给出这个算法的各个逻辑步骤。

代表这些具体逻辑步骤的⽅法称做基本⽅法(primitive method);⽽将这些基本⽅法汇总起来的⽅法叫做模板⽅法(template method),这个设计模式的名字就是从此⽽来。

模板⽅法所代表的⾏为称为顶级⾏为,其逻辑称为顶级逻辑。

模板⽅法模式的静态结构图如下所⽰: 这⾥涉及到两个⾓⾊: 抽象模板(Abstract Template)⾓⾊有如下责任: ■ 定义了⼀个或多个抽象操作,以便让⼦类实现。

这些抽象操作叫做基本操作,它们是⼀个顶级逻辑的组成步骤。

■ 定义并实现了⼀个模板⽅法。

这个模板⽅法⼀般是⼀个具体⽅法,它给出了⼀个顶级逻辑的⾻架,⽽逻辑的组成步骤在相应的抽象操作中,推迟到⼦类实现。

顶级逻辑也有可能调⽤⼀些具体⽅法。

具体模板(Concrete Template)⾓⾊⼜如下责任: ■ 实现⽗类所定义的⼀个或多个抽象⽅法,它们是⼀个顶级逻辑的组成步骤。

■ 每⼀个抽象模板⾓⾊都可以有任意多个具体模板⾓⾊与之对应,⽽每⼀个具体模板⾓⾊都可以给出这些抽象⽅法(也就是顶级逻辑的组成步骤)的不同实现,从⽽使得顶级逻辑的实现各不相同。

源代码 抽象模板⾓⾊类,abstractMethod()、hookMethod()等基本⽅法是顶级逻辑的组成步骤,这个顶级逻辑由templateMethod()⽅法代表。

public abstract class AbstractTemplate {/*** 模板⽅法*/public void templateMethod(){//调⽤基本⽅法abstractMethod();hookMethod();concreteMethod();}/*** 基本⽅法的声明(由⼦类实现)*/protected abstract void abstractMethod();/*** 基本⽅法(空⽅法)*/protected void hookMethod(){}/*** 基本⽅法(已经实现)*/private final void concreteMethod(){//业务相关的代码}} 具体模板⾓⾊类,实现了⽗类所声明的基本⽅法,abstractMethod()⽅法所代表的就是强制⼦类实现的剩余逻辑,⽽hookMethod()⽅法是可选择实现的逻辑,不是必须实现的。

钩子模型证明方式

钩子模型证明方式

钩子模型证明方式
钩子方法源于设计模式中模板方法(Template Method)模式,模板方法模式的概念为:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。

模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

其主要分为两大类:模版方法和基本方法,而基本方法又分为:抽象方法(Abstract Method),具体方法(Concrete Method),钩子方法(Hook Method)。

四种方法的基本定义(前提:在抽象类中定义):
(1)抽象方法:由抽象类声明,由具体子类实现,并以abstract 关键字进行标识。

(2)具体方法:由抽象类声明并且实现,子类并不实现或者做覆盖操作。

其实质就是普遍适用的方法,不需要子类来实现。

(3)钩子方法:由抽象类声明并且实现,子类也可以选择加以扩展。

通常抽象类会给出一个空的钩子方法,也就是没有实现的扩展。

它和具体方法在代码上没有区别,不过是一种意识的区别;而它和抽象方法有时候也是没有区别的,就是在子类都需要将其实现的时候。

而不同的是抽象方法必须实现,而钩子方法可以不实现。

也就是说钩子方法为你在实现某一个抽象类的时候提供了可选项,相当于预先提供了一个默认配置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Comparing the Template Method and Strategy Design Patterns in a Genetic Algorithm ApplicationMichael R. Wick and Andrew T. PhillipsComputer Science DepartmentUniversity of Wisconsin-Eau ClaireEau Claire, WI 54701{wickmr@, phillipa@}AbstractWe present a genetic algorithm software project that serves to give students direct experience with choosing among multiple potentially applicable design patterns. This project has been carefully constructed to illustrate the power of design patterns in supporting encapsulation while at the same time providing a single context in which to compare and contrast similar design pattern alternatives.1 IntroductionDesign patterns [1] are becoming ubiquitous within computer science education. And while not all educators agree on the proper location of design patterns in the computer science curriculum, nearly all educators agree that these generalized solutions to commonly recurring design problems represent a wealth of knowledge to which the undergraduate student should be exposed. We agree, but we also believe that no matter where in the curriculum design patterns are introduced, we must not simply present the patterns as a collection of tools, but we must also give the students hands-on experience with determining when and why each pattern is an appropriate design choice. Because students typically struggle with selecting the correct design pattern for a given problem, they typically either fail to see the applicability of a particular pattern, or they blindly apply their favorite pattern to problems for which it is not appropriate.As educators, we must focus our design pattern materials on applications that clearly illustrate to students the appropriate context in which to apply each pattern. This task is made even more difficult (but even more important) by the sometimes vague and overlapping applicability criteria presented in classic design pattern texts. In such cases, an ideal solution is to find a single application that clearly and unambiguously highlights the applicability criteria for each selected pattern, and that also effectively demonstrates the power that each distinct pattern provides.In this paper, we present such an application. We present a single software design project that helps clarify the distinction between two of the most fundamental design patterns – Template Method and Strategy. In so doing, the application not only correctly illustrates when and why one design pattern is more appropriate than the other, but also effectively illustrates the power of both patterns in achieving a dynamic, robust, and flexible design.2 MotivationEncapsulation is one of the most fundamental design principles that we teach students. This philosophy of isolating design decisions from one another is so instrumental in design that it occurs (or should occur) in nearly every undergraduate course in a modern computer science curriculum. It is both this ubiquitous presence of encapsulation and the support of encapsulation provided by the Template Method and Strategy design patterns that warrant our claim that the two patterns are two of the most important design patterns in current use.Of particular importance to us is the application of encapsulation to support multiple alternative implementations (we call this the variant behavior problem). When a design problem has multiple possible solutions, each with an associated cost and benefit, encapsulating separate design choices into separate class implementations isolates the impact of subsequent changes to the implementation and allows alternative implementations to be provided for use within varying application contexts.Both the Template Method and the Strategy design patterns provide structural models for solving the variant behavior problem. There is, of course, a fundamental distinction between them. To allow for alternative implementations, the Template Method pattern uses inheritance, while the Strategy pattern uses delegation. And the subtle implications of these two differing approaches can dramatically affect the quality of the resulting design.Given our premise that these patterns are of particular importance in that they support the fundamental design principle of encapsulation, we believe it is imperative that students be given an in-depth understanding of how to select the appropriate pattern. We have found that the implementation of a genetic algorithm simulator is an effective project for demonstrating this distinction to students. The genetic algorithm application is interesting and enjoyable, and it demands the full encapsulating power of both the Template Method and Strategy design patterns.3 BackgroundFor completeness, this section includes a brief introduction to genetic algorithms and the Template Method and Strategy design patterns.3.1 Genetic AlgorithmsA genetic algorithm is a search procedure based on the principles governing natural selection in a “survival of the fittest” biological world. John Holland did the original work on genetic algorithms in 1975 at the University of Michigan [3]. His work, and the work of his successors [2], focused attention on modeling the natural world in an attempt to provide an algorithmic abstraction of the adaptive process of natural systems.In a genetic algorithm, each potential solution to the problem is denoted by the term chromosome, which represents the encoded values of each of the variables of the problem. At the start of the genetic algorithm process, a collection, or initial generation, of randomly constructed chromosomes (potential solutions) is created. The genetic algorithm then follows a three-step process to transform the current generation of solutions to the next generation of solutions. This process provides a model of the natural world in which the only operators required for transforming solutions from one generation to the next are reproduction, crossover, and mutation.reproduction step selects from the current generation of chromosomes those that will survive to the next Thegeneration. This selection uses a probabilistic survival of the fittest mechanism based on a problem-specific evaluation of the chromosomes (modeling the concept of “fitness” from natural selection). This probabilistic survival mechanism is what directs the generations, over time, toward the most valuable (fit) chromosomes.Thecrossover step then allows the introduction of new chromosomes into the population of potential solutions by randomly combining pairs of randomly selected existing chromosomes. This step simulates the crossover phenomena in biological reproduction where two chromosomes mate by splitting into randomly selected subsections and then rejoining to form two new chromosomes. The key point here is that crossover allows new chromosomes not present in the current generation to be added to the next generation.mutation step allows the random mutation of existing chromosomes so that new chromosomes may Finally,thecontain parts not found in any existing chromosomes. Again, this step simulates the natural phenomena of gene mutation during reproduction. In the genetic algorithm process, mutation allows the introduction of new solution elements by permitting the occasional random alteration of a single element of the chromosome encoding.This three-step process is repeated, moving from generation to generation, until a generation is found that is “good enough”. There are many ways to determine when a generation is good enough, for example by using the “value” of the best chromosome in the population or by simply iterating for a fixed number of generations. When the process terminates, the best chromosome selected from among the final generation is the solution to the problem. The following also presents a summary of this genetic algorithm process.compute the initial generationwhile (more generations) {reproduce the current generationcrossover the current generationmutate the current generationincrement to the next generation}report the “best” solution in the generationThis genetic algorithm process has been shown to produce near optimal solutions to a wide variety of difficult optimization problems [2].3.2 The Template Method PatternThe Template Method pattern deals with the proper division of responsibility between parent and child classes in an inheritance hierarchy. The Template Method pattern solves to the variant behavior problem by allowing each child class to specify variant aspects of the object’s behavior while having the parent class define the invariant behavior that is common to all objects of this type. This is typically realized by providing an abstract parent class with amethod that defines the invariant steps that will be taken by all objects in response to a particular request. However, each step within this method is defined as an abstract method to be specified by each child class in order to obtainFigure 1the various desired behavioral options. The UML diagram in highlights this structure. ArrayFigure 1: The Template Method PatternThis structure supports behavioral variations of the resulting object by allowing each desired behavior to be defined in a separate child class.3.3 The Strategy PatternThe Strategy pattern also provides a solution to the variant behavior problem, but it does so by delegating the definition of each variant step of a process to a class in a separate inheritance hierarchy. This is typically realized again by providing the original class (called the “context class” in this pattern) with a method that defines the invariant behavior. However, rather than having a derived class provide the variant behavior, a separate object outside of the inheritance hierarchy is created and is held responsible for providing that behavior. The UML Figure 2diagram in highlights this structure.Figure 2: The Strategy PatternAs previously stated, this design pattern also supports alternative behaviors, but this time by using delegation rather than inheritance.4 Template Method versus StrategyIt is not difficult to see why students are confused over which of these patterns to select to achieve the desired variant behavior. The patterns are structurally similar and both support equally, at the highest level, the implementation of alternative behaviors. In fact, we have found that when left to their own accord, undergraduate students typically pick the pattern with which they are most comfortable and simply apply it any time they need to solve the variant behavior problem. Unfortunately, depending on the requirements of the application, the resulting design can be poor enough to offset the value of providing the variant behavior itself. The real problem is that it is not obvious to students that there are clear and specific reasons for choosing between the Template Method and Strategy patterns. In particular, the Strategy pattern should be selected when either of the following is true:¾The variant behaviors are applicable to a large class of differing client applications, and client data is typically accessed only through a general interface. In this situation, the variant behaviors can be reused in other unrelated applications that require the same variant behavior.¾The client application requires multiple variant methods (i.e. strategies), whose implementations do not require a maintained data representation that is shared between them.On the other hand, the Template Method pattern should be selected when either of the following is true instead: ¾The set of possible variant behaviors is specific to the client application, typically signaled by requiring unrestricted access to the client data.¾The client application requires multiple interrelated variant methods, frequently with a maintained shared data representation.While these rules are short and simple, conveying to students a true understanding of their motivation and implication is difficult. To be effective, each student must experience software design projects that illustrate the appropriate application of the rules. In the following sections, we present a genetic algorithm application that uses these rules to identify the appropriate but separate application of both the Template Pattern and the Strategy Pattern in a single project.5 The Genetic Algorithm ApplicationIn this section we present the design of a genetic algorithm framework that effectively uses both the Template Method and Strategy design patterns. The genetic algorithm framework has the added benefit of providing a natural context in which to support a collection of variant behavioral definitions, each with specific implications on the overall effectiveness of the framework for solving particular problems.Our genetic algorithm application is a framework (hereafter called the GAF – Genetic Algorithm Framework) that can be used to solve a wide variety of optimization problems. Like most frameworks, the GAF is domain-independent, providing hooks for the domain-dependent aspects of each application. The GAF provides the code for maintaining the collection of chromosomes and for performing the standard reproduce, crossover, and mutate operations on that collection. But it leaves the specific definition, or encoding, of the chromosome itself to the user of the framework, since the chromosome represents the domain-dependent problem representation manipulated byigure 3the GAF. A simplified UML diagram for the overall design is shown in F. In the next section we discuss this design in detail.Figure 3: The Genetic Algorithm Framework5.1 The Genetic Algorithm Class ModelWhile there are many supporting classes (like iterators, containers, etc), the core of the GAF consists of an integrated collection of four abstract classes (GeneticAlgorithm, Reproduce, Crossover, Mutate) and one interface (Chromosome) for connection to the application domain.GeneticAlgorithm is an abstract class that represents the heart of the genetic algorithm process. This class uses the Template Method pattern to define the standard three-step sequence required of a genetic algorithm, while leaving the details of algorithm initialization, iteration, and termination to a choice of derived and concrete subclasses. The lower left side of Figure 3 illustrates how we elected to implement this variant behavior by using a concrete FixedIterationGeneticAlgorithm subclass of GeneticAlgorithm.Note that the abstract methods initializeGenerations, incrementGeneration, and moreGenerations in GeneticAlgorithm represent the template steps in the genetic algorithm process. These three methods together handle the transformation of chromosomes from one generation to the next. The Template Method pattern is appropriate in this context since the definitions of these three operations are highly interrelated, frequently sharing at least one common data structure. For example, one possible implementation choice is to select a FixedIterationGeneticAlgorithm subclass that uses a fixed generation count to determine when to stop the genetic evolution process. In this case, FixedIterationGeneticAlgorithm defines an integer count that is set to zero by initializeGenerations, is incremented by incrementGeneration, and is compared to some fixed maximum in moreGenerations. Of course, other approaches could be used instead. For instance, the implementation of a StabilityGeneticAlgorithm subclass could use a population measure based on “stability” to stop the genetic algorithm when m successive generations produce equal-valued results. Notice how this use of the Template Method pattern supports the required variant behavior natural to the application. The user of the GAF can tailor the generation maintenance implementation to fit the specific requirements of the application domain.On the other hand, each of the reproduce, crossover, and mutate steps of the genetic algorithm process are implemented using the Strategy pattern (see the right side of Figure 3). For brevity, we describe only the reproduce step here, since the crossover and mutate steps are analogous. The Reproduce class serves as the abstract class from which all concrete reproduction strategies are derived.The GeneticAlgorithm class invokes a concrete reproduction strategy by delegating this responsibility to the reproduce method of a ReproductionStrategy instance variable (local to the GeneticAlgorithm class). In this case, the abstract class ReproductionStrategy provides the hook in the genetic algorithm process for any specific reproduction strategy desired. One particular strategy that can be implemented is the “value proportional” strategy in which chromosomes survive to the next generation with a probability equal to their value divided by the value of the best chromosome in the current generation. Of course, many other concrete strategies would be possible here as well. The solve method of the GeneticAlgorithm class delegates the act of reproduction to the concrete class using dynamic typing to invoke the appropriate subclass reproduce method. Similarly, abstract classes for CrossoverStrategy and for MutationStrategy provide the hooks in the genetic algorithm process required to implement the other two steps of the genetic algorithm process.The use of the Strategy pattern for the reproduce, crossover, and mutate steps allows the user to easily experiment with any combination of strategies for these steps. Because each strategy is isolated in its own class and doesn’t share any maintained data structures, the strategies are independent and can be mixed and matched as appropriate. This is in direct contrast to the generation-manipulation methods that are inherently dependent on one another through a shared and maintained data structure. Using the pattern selection rules from section 4, the reproduce, crossover, and mutate steps call for the Strategy Pattern while the generation initialization, increment, and termination steps motivate the use the Template Method pattern.Notice that all of the code of the GAF presented so far is domain-independent in that it doesn’t depend on the particular problem being solved. The Chromosome interface provides this problem specific connection, and the entire GAF is written to work with any domain-specific class that adheres to the Chromosome interface. The Chromosome interface itself is very simple. It requires a crossoverWith method that defines how two chromosomes crossover, a mutate method that defines how a chromosome mutates, and a valueOf method that defines the “value” of a specific chromosome. Notice how the framework itself does not impose a particular problem representation or encoding on the application; the application can be represented in whatever design is appropriate as long as the design supports those three required manipulation methods.6 Role in the CurriculumThe implementation of a genetic algorithm framework is a substantive project for undergraduate students at any level. However, we believe that this application could appropriately be used in at least two places. First, and most obviously, the genetic algorithm project could be given as a 2-3 week programming assignment within a senior-level design patterns course. Arguably, this is the point at which a student is most likely to comprehend the subtle and important distinctions between these two patterns. Second, we believe the genetic algorithm application is appropriate as a program-in-progress style project for a freshman-level introduction to programming course. If developed as part of a lecture or closed-laboratory sequence, even such inexperienced programmers could be asked to implement portions of the application giving them early hands-on experience with the competing options of inheritance versus delegation.At UW-Eau Claire, we have used the application in both contexts. The application was originally developed in an advanced course on design patterns and later adapted for use in our CS1 course.7 SummaryWe have presented a programming application that serves to gives students hands-on experience with making the appropriate selection between two alternative design patterns, the Template Method and Strategy patterns. These design patterns are of particular importance as they directly support the fundamental design concept of encapsulation.Complete Java code for the genetic algorithm application is available from the authors.References[1] E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of Reuseable Object-OrientedSoftware. Addison-Wesley Publishing (1995).[2] D. Goldberg. Genetic Algorithms in Search, Optimization & Machine Learning. Addison-Wesley Publishing(1989).[3]J. Holland. Adaptation in Natural and Artificial Systems. The University of Michigan Press, Ann Arbor (1975).。

相关文档
最新文档