Design Pattern----26.Behavioral.TemplateMethod.Pattern (Delphi Sample)

Intent

  • Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  • Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.

Problem

Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.

Discussion

The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent “hooks”, or “placeholders”, that can, or must, be supplied by the component’s client in a concrete derived class.

The component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps.

Template Method is used prominently in frameworks. Each framework implements the invariant pieces of a domain’s architecture, and defines “placeholders” for all necessary or interesting client customization options. In so doing, the framework becomes the “center of the universe”, and the client customizations are simply “the third rock from the sun”. This inverted control structure has been affectionately labelled “the Hollywood principle” - “don’t call us, we’ll call you”.

Structure

Template Method scheme

The implementation of template_method() is: call step_one(), call step_two(), and call step_three(). step_two() is a “hook” method – a placeholder. It is declared in the base class, and then defined in derived classes. Frameworks (large scale reuse infrastructures) use Template Method a lot. All reusable code is defined in the framework’s base classes, and then clients of the framework are free to define customizations by creating derived classes as needed.

Template Method scheme

Example

The Template Method defines a skeleton of an algorithm in an operation, and defers some steps to subclasses. Home builders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number of floor plans with different variations available for each. Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models.

Template Method example

Check list

  1. Examine the algorithm, and decide which steps are standard and which steps are peculiar to each of the current classes.
  2. Define a new abstract base class to host the “don’t call us, we’ll call you” framework.
  3. Move the shell of the algorithm (now called the “template method”) and the definition of all standard steps to the new base class.
  4. Define a placeholder or “hook” method in the base class for each step that requires many different implementations. This method can host a default implementation – or – it can be defined as abstract (Java) or pure virtual (C++).
  5. Invoke the hook method(s) from the template method.
  6. Each of the existing classes declares an “is-a” relationship to the new abstract base class.
  7. Remove from the existing classes all the implementation details that have been moved to the base class.
  8. The only details that will remain in the existing classes will be the implementation details peculiar to each derived class.

Rules of thumb

  • Strategy is like Template Method except in its granularity.
  • Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
  • Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
  • Factory Method is a specialization of Template Method.

Template Method in Delphi

Applications in Delphi

Abstraction is implemented in Delphi by abstract virtual methods. Abstract methods differ from virtual methods by the base class not providing any implementation. The descendant class is completely responsible for implementing an abstract method. Calling an abstract method that has not been overridden will result in a runtime error.

A typical example of abstraction is the TGraphic class.

TGraphic is an abstract class used to implement TBitmap, TIcon and TMetafile. Other developers have frequently used TGraphic as the basis for other graphics objects such as PCX, GIF, JPG representations. TGraphic defines abstract methods such as Draw, LoadFromFile and SaveToFile which are then overridden in the concrete classes. Other objects that use TGraphic, such as a TCanvas only know about the abstract Draw method, yet are used with the concrete class at runtime.

Many classes that use complex algorithms are likely to benefit from abstraction using the template method approach. Typical examples include data compression, encryption and advanced graphics processing.

Implementation Example

To implement template methods you need an abstract class and concrete classes for each alternate implementation. Define a public interface to an algorithm in an abstract base class. In that public method, implement the steps of the algorithm in calls to protected abstract methods of the class. In concrete classes derived from the base class, override each step of the algorithm with a concrete implementation specific to that class.

This example shows some very simple alogrithm steps, but illustrates the principle of deferring implementation to a subclass.

 
 
  1: unit Tpl_meth;
  2: 
  3: interface
  4: 
  5: type
  6: 
  7:   TAbstractTemplateClass = class(TObject)
  8:   protected
  9:     function Algorithm_StepA: Integer; virtual; abstract;
 10:     function Algorithm_StepB: Integer; virtual; abstract;
 11:     function Algorithm_StepC: Integer; virtual; abstract;
 12:   public
 13:     function Algorithm: Integer;
 14:   end;
 15: 
 16:   TConcreteClassA = class(TAbstractTemplateClass)
 17:   protected
 18:     function Algorithm_StepA: Integer; override;
 19:     function Algorithm_StepB: Integer; override;
 20:     function Algorithm_StepC: Integer; override;
 21:   end;
 22:  
 23:   TConcreteClassB = class(TAbstractTemplateClass)
 24:   protected
 25:     function Algorithm_StepA: Integer; override;
 26:     function Algorithm_StepB: Integer; override;
 27:     function Algorithm_StepC: Integer; override;
 28:   end;
 29: 
 30:   ...
 31: 

转载于:https://www.cnblogs.com/xiuyusoft/archive/2011/07/01/2095454.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
“设计模式:可重用的面向对象软件的基本元素(Design Patterns: Elements of Reusable Object-Oriented Software)”是一本由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 四人所著的经典书籍。该书于1994年首次出版,被誉为“软件设计模式圣经”。 该书讲述了一些经典的设计模式,包括面向对象编程中涉及到的对象、类、接口和继承等基本概念,并详细介绍了在实际应用中如何使用这些模式来解决常见的设计问题。 该书的主要内容包括:介绍了23种设计模式,其中分为创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)三种类型;每个设计模式包括模式的定义、优点、结构以及应用场景等方面,以及一些常见的解决方案;此外,该书还特别强调了设计模式的重要性,并简要介绍了如何利用设计模式提高代码的可维护性和可重用性等方面。 该书的读者主要包括软件开发人员、软件架构师、系统设计师等技术人员,也适合经验较浅的Java、C++和C#等编程语言的初学者,读过该书后可以深刻理解并熟练运用设计模式来提高软件开发的效率和质量。 在CSDN(中文技术社区)上,设计模式是一门热门的技术,有很多人通过阅读“设计模式:可重用的面向对象软件的基本元素”这本书籍,来掌握设计模式的基础知识,并学习如何在实际项目中应用这些模式。该书也经常被提及在CSDN社区中的技术讨论中,并被认为是学习设计模式最权威的教材之一。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值