• TemplateMethod模式


    Template Method模式的几个角色:

    基类角色:定义的抽象方法、纯虚方法(一般设置为protected),Template方法(是对抽象方法、纯虚方法包装).
    子类角色:重写基类抽象方法、纯虚方法.
    客户端角色:调用子类中的重写过的方法.

    演示代码如下:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    namespace TemplateMethod
    {
        
    class Program
        
    {
            
    public abstract class Computer //表示电脑(基类角色)
            {
                
    protected abstract void Start();
                
    protected abstract void Close();

                
    public void TemplateMethod()//Template Method使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

                
    {
                    Start();
    //开电脑
                    Close();//关闭电脑 

                }

            }


            
    //子类角色
            public class Lenovo : Computer //我上班用的联想电脑
            {
                
    protected override void Start()
                
    {
                    Console.WriteLine(
    "上班了把联想电脑打开");

                }


                
    protected override void Close()
                
    {
                    Console.WriteLine(
    "下班了把联想电脑关闭");
                }


             
            }

            
            
    public class ComputerTest
            
    {
                
    public static void DoTest(Computer cp) //早上上班要打开电脑测试
                {

                    cp.TemplateMethod();

                }

            }


            
    //客户端角色
            public static void Main()
            
    {
               ComputerTest.DoTest(
    new Lenovo());//早上上班要打开我的联想电脑
               
    //Computer test=new Lenovo();
               
    //ComputerTest.DoTest(test);
            }


        }

    }



    Template Method模式的实质就是在基类定义一个Template 再在子类中重写Template中的具体方法,以便客户端访问.
  • 相关阅读:
    【亲身测试成功】windows7 32位操作系统 环境下安装 windows7 64位操作系统
    Deprecated: Function ereg_replace() is deprecated in ……【解决方法】
    20100526(开始上班咯···)
    20100608
    String与string的区别
    Jquery CheckBox全选方法
    与技术无关
    jquery之对象访问(是不是API里出错了呢?)
    工作四个月之后的小感
    关于数据库中的AK(Alternate Key)
  • 原文地址:https://www.cnblogs.com/xiaobaigang/p/911018.html
Copyright © 2020-2023  润新知