Design Pattern - Template Method(C )

Definition

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.

Participants

The classes and/or objects participating in this pattern are:

  • AbstractClass (DataObject)

    • Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm
    • Implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects
  • ConcreteClass (CustomerDataObject)
    • Implements the primitive operations or carry out subclass-specific steps of the algorithm

Sample Code in C#

This structural code demonstrates the Template method which provides a skeleton calling sequence of methods. One or more steps can be deferred to subclasses which implement these steps without changing the overall calling sequence.

// Template Method pattern - Structural example                    

namespace CSharpLearning
{
    using System;

    /// <summary>
    /// Startup class for Real-World Template Method design pattern.
    /// </summary>
    public class MainApp
    {
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        public static void Main()
        {
            AbstractClass aA = new ConcreteClassA();
            aA.TemplateMethod();

            AbstractClass aB = new ConcreteClassB();
            aB.TemplateMethod();

            // Wait for user.
            Console.ReadKey();
        }
    }

    /// <summary>
    /// The ‘AbstractClass‘ abstract class.
    /// </summary>
    public abstract class AbstractClass
    {
        /// <summary>
        /// The primitive operation 1.
        /// </summary>
        public abstract void PrimitiveOperation1();

        /// <summary>
        /// The primitive operation 2.
        /// </summary>
        public abstract void PrimitiveOperation2();

        /// <summary>
        /// The template method.
        /// </summary>
        public void TemplateMethod()
        {
            this.PrimitiveOperation1();
            this.PrimitiveOperation2();
            Console.WriteLine(string.Empty);
        }
    }

    /// <summary>
    /// A ‘ConcreteClass‘ class.
    /// </summary>
    public class ConcreteClassA : AbstractClass
    {
        /// <summary>
        /// The primitive operation 1.
        /// </summary>
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("ConcreteClassA.PrimitiveOperation1()");
        }

        /// <summary>
        /// The primitive operation 2.
        /// </summary>
        public override void PrimitiveOperation2()
        {
            Console.WriteLine("ConcreteClassA.PrimitiveOperation2()");
        }
    }

    /// <summary>
    /// A ‘ConcreteClass‘ class.
    /// </summary>
    public class ConcreteClassB : AbstractClass
    {
        /// <summary>
        /// The primitive operation 1.
        /// </summary>
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("ConcreteClassB.PrimitiveOperation1()");
        }

        /// <summary>
        /// The primitive operation 2.
        /// </summary>
        public override void PrimitiveOperation2()
        {
            Console.WriteLine("ConcreteClassB.PrimitiveOperation2()");
        }
    }
}

// Output:
/*
ConcreteClassA.PrimitiveOperation1()
ConcreteClassA.PrimitiveOperation2()

ConcreteClassB.PrimitiveOperation1()
ConcreteClassB.PrimitiveOperation2()
*/


This real-world code demonstrates a Template method named Run() which provides a skeleton calling sequence of methods. Implementation of these steps are deferred to the CustomerDataObject subclass which implements the Connect, Select, Process, and Disconnect methods.

// Template Method pattern - Real World example

namespace CSharpLearning
{
    using System;
    using System.Data;
    using System.Data.OleDb;

    /// <summary>
    /// Startup class for Real-World Template Design Pattern.
    /// </summary>
    public class MainApp
    {
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        public static void Main()
        {
            DataAccessObject daoCategories = new Categories();
            daoCategories.Run();

            DataAccessObject daoProducts = new Products();
            daoProducts.Run();

            // Wait for user.
            Console.ReadKey();
        }
    }

    /// <summary>
    /// The ‘AbstractClass‘ abstract class.
    /// </summary>
    public abstract class DataAccessObject
    {
        /// <summary>
        /// The connection string.
        /// </summary>
        protected string ConnectionString;

        /// <summary>
        /// The data set.
        /// </summary>
        protected DataSet DataSet;

        /// <summary>
        /// The connect.
        /// </summary>
        public virtual void Connect()
        {
            // Make sure mdb is available to app.
            this.ConnectionString = "provider=Microsoft.JET.OLEDB.4.0; data source=..\\..\\..\\db1.mdb";
        }

        /// <summary>
        /// The select.
        /// </summary>
        public abstract void Select();

        /// <summary>
        /// The process.
        /// </summary>
        public abstract void Process();

        /// <summary>
        /// The disconnect.
        /// </summary>
        public virtual void Disconnect()
        {
            this.ConnectionString = string.Empty;
        }

        /// <summary>
        /// The ‘Template Method‘.
        /// </summary>
        public void Run()
        {
            this.Connect();
            this.Select();
            this.Process();
            this.Disconnect();
        }
    }

    /// <summary>
    /// A ‘ConcreteClass‘ class.
    /// </summary>
    public class Categories : DataAccessObject
    {
        /// <summary>
        /// The select.
        /// </summary>
        public override void Select()
        {
            const string Sql = "select CategoryName from Categories";
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(Sql, this.ConnectionString);
            this.DataSet = new DataSet();
            dataAdapter.Fill(this.DataSet, "Categories");
        }

        /// <summary>
        /// The process.
        /// </summary>
        public override void Process()
        {
            Console.WriteLine("Categories ---- ");
            DataTable dataTable = this.DataSet.Tables["Categories"];
            foreach (DataRow row in dataTable.Rows)
            {
                Console.WriteLine(row["CategoryName"]);
            }

            Console.WriteLine();
        }
    }

    /// <summary>
    /// A ‘ConcreteClass‘ class.
    /// </summary>
    public class Products : DataAccessObject
    {
        /// <summary>
        /// The select.
        /// </summary>
        public override void Select()
        {
            const string Sql = "select ProductName from Products";
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(Sql, this.ConnectionString);
            this.DataSet = new DataSet();
            dataAdapter.Fill(this.DataSet, "Products");
        }

        /// <summary>
        /// The process.
        /// </summary>
        public override void Process()
        {
            Console.WriteLine("Products ---- ");
            DataTable dataTable = this.DataSet.Tables["Products"];
            foreach (DataRow row in dataTable.Rows)
            {
                Console.WriteLine(row["ProductName"]);
            }

            Console.WriteLine();
        }
    }
}

// Output:
/*

Categories ----
Beverages
Condiments
Confections
Dairy Products
Grains/Cereals
Meat/Poultry
Produce
Seafood

Products ----
Chai
Chang
Aniseed Syrup
Chef Anton‘s Cajun Seasoning
Chef Anton‘s Gumbo Mix
Grandma‘s Boysenberry Spread
Uncle Bob‘s Organic Dried Pears
Northwoods Cranberry Sauce
Mishi Kobe Niku
*/

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

原文地址:https://www.cnblogs.com/kwincaq/p/10113267.html

时间: 2024-11-05 14:43:28

Design Pattern - Template Method(C )的相关文章

Head First Design Pattern 读书笔记(2) 观察者模式

Head First Design Pattern 读书笔记(2) Observer Pattern 观察者模式 Observer Pattern 类图 定义 观察者模式:在对象间定义一个一对多的关系,当其中一个的对象发生改变时,所有依赖于这个对象的对象(即观察者们)都会自动更新或做执行某些行为. 几个OO的原测 尽量以松耦合的方式处理对象间关系–>软件工程时候学的"高內聚,低耦合"的好处 关于观察者模式 被观察对象通知观察者可以使用推送的方式(类图中带参数的notifyActi

Head First Design Pattern 读书笔记(1) 策略模式

Head First Design Pattern 读书笔记(1) Strategy Pattern 策略模式 这几天为了锻炼看英语文档的能力,开着有道硬着头皮看 <Head First Desgin Pattern>的原版书,顺便做下笔记,把里面提到的每个模式通过回忆的方式画出来复习并记下来总结下学习成果=.= 关于设计模式 使用设计模式是为了增强程序的复用性,拓展性,易维护性. 设计模式会增加程序代码的复杂度,并不是所有情况都必须使用设计模式,需要根据需求以及经验评估使用场景. 学习并掌握

Head First Design Pattern 读书笔记(4) 单例模式

Head First Design Pattern 读书笔记(4) Singleton Pattern 单例模式 Silngleton Pattern 类图 单例模式非常简单,基本没有什么类之间的关系,就不画图了,保证某个类生成的实例只有一个即可. 定义 单例模式:只允许一个类实例化一个对象,并提供一个可以全局访问这个实例的方法(接口). 关于单例模式 最简单的单例模式实现方法是: /* *"懒汉式"写法,即等要用了再去实例化实例对象,而不是应用一启动就实例化好放在容器中. */ pu

Head First Design Pattern 读书笔记(3)装饰者模式

Head First Design Pattern 读书笔记(3) Decorator Pattern 装饰者模式 Decorator Pattern 类图 定义 装饰者模式:通过让组件类与装饰者类实现相同的接口,装饰类可以在不修改原有组件类的情况下,动态拓展组件类的新功能,并且可以无限拓展下去. 几个OO的原测 类应该对修改关闭,对拓展开放.–>"开闭原则",即尽量不要修改已经在用的类,而通过继承的方式去拓展类的新功能. 设计类时应当尽量考虑不修改原有的代码.–>同&qu

Template Method(模板方法)模式

1.概述 在面向对象开发过程中,通常我们会遇到这样的一个问题:我们知道一个算法所需的关键步骤,并确定了这些步骤的执行顺序.但是某些步骤的具体实现是未知的,或者说某些步骤的实现与具体的环境相关.例子1:银行业务办理流程在银行办理业务时,一般都包含几个基本固定步骤:取号排队->办理具体业务->对银行工作人员进行评分.取号取号排队和对银行工作人员进行评分业务逻辑是一样的.但是办理具体业务是个不相同的,具体业务可能取款.存款或者转账. 2.问题 如何保证架构逻辑的正常执行,而不被子类破坏 ? 3.解决

错误信息:Bean property &#39;sessionFactory&#39; is not writable or has an invalid setter method.(Springmvc)

是在建立class的时候对应的set方法和spring配置文件的不一样 public class GoodsService implements IGoodsService{private IGoodDAO goodsDao; public void setGoodsDao(IGoodDAO goodsDao) { this.goodsDao = goodsDao;} } public class GoodDAO implements IGoodDAO{private SessionFactor

Waves:类Material Design 的圆形波浪(涟漪)点击特效插件

Google Material Design 相信你也了解不少了,但目前无论是应用端还是网页端,可参考案例尚少.本着补充<Material Design 一些相关中文资料/资源收集汇总>一文的目的,介绍一款类Google Material Design 的圆形波浪(涟漪)点击特效插件Waves. Google Material Design 中有一个特效,点击某个色块区域会有圆形波浪(涟漪)渐现放大的效果(当然,对应应用端则为触摸事件).Waves 就是这么一款在网页上实现该特效的javasc

设计模式 ( 十九 ) 模板方法模式Template method(类行为型)

1.概述 在面向对象开发过程中,通常我们会遇到这样的一个问题:我们知道一个算法所需的关键步骤,并确定了这些步骤的执行顺序.但是某些步骤的具体实现是未知的,或者说某些步骤的实现与具体的环境相关.例子1:银行业务办理流程在银行办理业务时,一般都包含几个基本固定步骤:取号排队->办理具体业务->对银行工作人员进行评分.取号取号排队和对银行工作人员进行评分业务逻辑是一样的.但是办理具体业务是个不相同的,具体业务可能取款.存款或者转账. 2.问题 如何保证架构逻辑的正常执行,而不被子类破坏 ? 3.解决

C++ template —— template metaprogram(九)

metaprogramming含有“对一个程序进行编程”的意思.换句话说,编程系统将会执行我们所写的代码,来生成新的代码,而这些新代码才真正实现了我们所期望的功能.通常而言,metaprogramming这个概念意味着一种反射的特性:metaprogramminig组件只是程序的一部分,而且它也只生成一部分代码或者程序. 使用metaprogramming的目的是为了实现更多的功能,并且是花费的开销(代码大小,维护的开销等来衡量)更小.另一方面,metaprogramming的最大特点在于:某些