怎么样免费创建网站,设计图ai生成,wordpress网站主机,外贸商做英文网站的目的Linux C 053-设计模式之模板方法模式
本节关键字#xff1a;Linux、C、设计模式、模板方法模式 相关库函数#xff1a;
概念
模板方法模式定义了一个算法的步骤#xff0c;并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下#xff0c;重新…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
*/