10.模板方法模式

模板方法模式,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

一 模板方法模式练习-试卷

UML图

测试代码

cpp 复制代码
#include <iostream>
using namespace std;
 
class TestPaper
{
public:
    void question2(){
        cout << "试题2" << endl;
        cout << "答案:" << answer2() << endl;
    }
    void question1(){
        cout << "试题1" << endl;
        cout << "答案:" << answer1() << endl;
    }
    virtual string answer1() = 0;
    virtual string answer2() = 0;
};
 
class TestPaperA:public TestPaper
{
public:
    virtual string answer1(){
        return "a";
    }
    virtual string answer2(){
        return "a";
    }
};
 
class TestPaperB:public TestPaper
{
public:
    virtual string answer1(){
        return "b";
    }
    virtual string answer2(){
        return "b";
    }
};
 
int main(void)
{
    cout << "学生a的试卷:" << endl;
    TestPaper *a = new TestPaperA();
    a->question1();
    a->question2();
 
    cout << "学生b的试卷:" << endl;
    TestPaper *b = new TestPaperB();
    b->question1();
    b->question2();
    return 0;
}

二、模板方法模式

UML


代码

cpp 复制代码
#include <iostream>
using namespace std;
 
class communication
{
public:
    void process(){
        read();
        write();
    }
    virtual int read() = 0;
    virtual int write() = 0;
};
class uart:public communication
{
public:
    int read(){
        cout << "读串口" << endl;
        return 0;
    }
    int write(){
        cout << "写串口" << endl;
        return 0;
    }
};
class tcp:public communication
{
public:
    int read(){
        cout << "读tcp" << endl;
        return 0;
    }
    int write(){
        cout << "写tcp" << endl;
        return 0;
    }
};
class udp:public communication
{
public:
    int read(){
        cout << "读udp" << endl;
        return 0;
    }
    int write(){
        cout << "写udp" << endl;
        return 0;
    }
};
 
 
int main(void)
{
    communication *u = new uart();
    communication *t = new tcp();
    communication *d = new udp();
    u->process();
    t->process();
    d->process();
    return 0;
}

运行结果:

复制代码
读串口
写串口
读tcp
写tcp
读udp
写udp
相关推荐
ArabySide2 小时前
【Java】重构之善用多态解耦,记录一次模板方法实践
java·重构·模板方法模式
Poetinthedusk13 小时前
设计模式-模板方法模式
windows·设计模式·c#·wpf·模板方法模式
山风wind3 天前
设计模式-模板方法模式详解
python·设计模式·模板方法模式
mylinke4 天前
基于YALMIP的微网优化调度模型探索
模板方法模式
__万波__4 天前
二十三种设计模式(十三)--模板方法模式
java·设计模式·模板方法模式
ZHE|张恒20 天前
设计模式(十四)模板方法模式 — 定义流程骨架,把步骤差异留给子类
设计模式·模板方法模式
miss_you12131 个月前
策略模式 + 模板方法 + 注册式工厂 统一设计方案(营销优惠场景示例)
设计模式·工厂方法模式·策略模式·模板方法模式
张小洛1 个月前
Spring JDBC源码解析:模板方法模式的优雅实践
数据库·spring·模板方法模式·spring jdbc
bkspiderx2 个月前
C++设计模式之行为型模式:模板方法模式(Template Method)
c++·设计模式·模板方法模式
o0向阳而生0o2 个月前
108、23种设计模式之模板方法模式(17/23)
设计模式·模板方法模式