zoukankan      html  css  js  c++  java
  • 模板方法模式

    1】什么是模板方法模式?
    
    又叫模板方法模式,在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。
    
    模板方法使得子类可以在不改变算法结构的情冴下,重新定义算法中的某些步骤。
    
    【2】模板方法模式代码示例:
    
    代码示例1:
    #include <iostream>
    #include <string>
    using namespace std;
    
    class TestPaper
    {
    public:
        void question1()
        {
            cout << "1+1=" << answer1() << endl;
        }
        void question2()
        {
            cout << "1*1=" << answer2() << endl;
        }
        virtual string answer1()
        {
            return "";
        }
        virtual string answer2()
        {
            return "";
        }
        virtual ~TestPaper()
        {
        }
    };
    
    class TestPaperA : public TestPaper
    {
    public:
        string answer1()
        {
            return "2";
        }
        virtual string answer2()
        {
            return "1";
        }
    };
    
    class TestPaperB : public TestPaper
    {
    public:
        string answer1()
        {
            return "3";
        }
        virtual string answer2()
        {
            return "4";
        }
    };
    
    
    int main()
    {
        cout << "A的试卷:" << endl;
        TestPaper *s1 = new TestPaperA();
        s1->question1();
        s1->question2();
        delete s1;
    
        cout << endl;
        cout << "B的试卷:" << endl;
        TestPaper *s2 = new TestPaperB();
        s2->question1();
        s2->question2();
    
        return 0;
    }
    代码示例2:
    #include<iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    class AbstractClass
    {
    public:
        void Show()
        {
            cout << "我是" << GetName() << endl;
        }
    protected:
        virtual string GetName() = 0;
    };
    
    class Naruto : public AbstractClass
    {
    protected:
        virtual string GetName()
        {
            return "火影史上最帅的六代目---一鸣惊人naruto";
        }
    };
    
    class OnePice : public AbstractClass
    {
    protected:
        virtual string GetName()
        {
            return "我是无恶不做的大海贼---路飞";
        }
    };
    
    //客户端
    int main()
    {
        Naruto* man = new Naruto();
        man->Show();
    
        OnePice* man2 = new OnePice();
        man2->Show();
    
        return 0;
    }
  • 相关阅读:
    delphi RTTI 反射技术
    delphi 自我删除和线程池(1000行代码,需要仔细研究)
    寻找两个已序数组中的第k大元素
    OpenCV中的神器Image Watch
    PYTHON 之 【RE模块的正则表达式学习】
    Call U
    微软IE11浏览器的7大变化
    集群应用及运维经验小结
    逆序对:从插入排序到归并排序
    Jquery 图片轮播实现原理总结
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4534636.html
Copyright © 2011-2022 走看看