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;
    }
  • 相关阅读:
    gitio博客搭建,hexo + NeXT
    [MIsc]JD笔试编程题
    [MATH]Big Integer +
    【Math】GCD XOR 证明
    【Math】最近点对
    【SRM】600#div2 B 枚举
    【Game】组合游戏
    【Game】找出游戏必胜态
    【DP】树形DP 记忆化搜索
    141. Linked List Cycle
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4534636.html
Copyright © 2011-2022 走看看