您的位置:首页 > 汽车 > 新车 > Linux C++ 053-设计模式之模板方法模式

Linux C++ 053-设计模式之模板方法模式

2024/10/18 13:00:45 来源:https://blog.csdn.net/qq_45157350/article/details/135869850  浏览:    关键词:Linux C++ 053-设计模式之模板方法模式

Linux C++ 053-设计模式之模板方法模式

本节关键字:Linux、C++、设计模式、模板方法模式
相关库函数:

概念

模板方法模式定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。在软件工程中,它是一种软件设计模式,和C++模板没有关连。

使用场景

模板方法模式多用在:

1、某些类别的算法中,实做了相同的方法,造成程式码的重复。

2、控制子类别必须遵守的一些事项。

代码示例

// 将不变的代码都移到父类中,将可变的方法用virture留到子类中重写
// 需要重写的方法都放在了protected关键字下
// 父类中无需重写的方法来调用需要重写的方法
// 客户端只需访问类中无需重写的方法class Computer
{
public:void product() {installCPU();installRAM();installGraphicsCard();}
private:virtual void installCPU() = 0;virtual void installRAM() = 0;virtual void installGraphicsCard() = 0;
};
class ComputerA : public Computer
{
protected:void installCPU() override {cout << "ComputerA install Inter Core i5" << endl;}void installRAM() override {cout << "ComputerA install 2G Ram" << endl;}void installGraphicsCard() override {cout << "ComputerA install Gtx940 GraohicsCard" << endl;}
};
class ComputerB : public Computer
{
protected:void installCPU() override {cout << "ComputerB install Inter Core i7" << endl;}void installRAM() override {cout << "ComputerB install 4G Ram" << endl;}void installGraphicsCard() override {cout << "ComputerB install Gtx960 GraohicsCard" << endl;}
};
int main_Model()
{ComputerB* c1 = new ComputerB();c1->product();c1 = NULL;return 0;
}
/* 运行结果:
ComputerB install Inter Core i7
ComputerB install 4G Ram
ComputerB install Gtx960 GraphicsCard
*/

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com