策略模式
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
优点:替代了继承,降低了耦合性
#include <iostream>
using namespace std;
/*我们来陪电脑*/
class Base{
protected:
string name;
public:
Base()
{
}
Base(string name)
{
this->name=name;
}
void show()
{
cout<<name<<endl;
}
};
class Graphics:public Base{
public:
Graphics()
{
this->name="AMD";
}
Graphics(string name):Base(name){
}
/*省略了修改name的函数*/
};
class CPU:public Base{
public:
CPU()
{
this->name="i5";
}
CPU(string name):Base(name)
{
}
//.....
};
class computer{
private:
Graphics *graphics;
CPU *cpu;
public:
computer()
{
this->graphics=new Graphics();
this->cpu=new CPU();
}
void show()
{
cout<<"电脑的配置为"<<endl;
graphics->show();
cpu->show();
}
};
int main(void)
{
computer *p=new computer();
p->show();
return 0;
}