合成复用原则

来源:互联网 发布:java 触发器 开源 编辑:程序博客网 时间:2024/05/16 09:54
#include<iostream>
using namespace std;


//合成复用原则:对于继承和组合,优先使用组合


//抽象车
class AbstractCar
{
public:
virtual void run() = 0;
};
//大众车
class DaZhong : public AbstractCar
{
public:
virtual void run()
{
cout<<"大众车启动..."<<endl;
}
};
//拖拉机
class TuoLaJi : public AbstractCar
{
public:
virtual void run()
{
cout<<"拖拉机启动..."<<endl;
}
};
//可以使用组合,将车作为人的成员变量
class Person
{
public:
void setCar(AbstractCar* car)
{
this->car=car;
}
void Doufeng()
{
this->car->run();
if(this->car!=NULL)
{
delete this->car;
this->car=NULL;
}
}
public:
AbstractCar* car;
};
void test02()
{
Person* p = new Person;
p->setCar(new DaZhong);
p->Doufeng();//空间释放在函数里面进行释放


p->setCar(new TuoLaJi);
p->Doufeng();//空间释放在函数里面进行释放


delete p;
}
int main(void)
{
test02();
system("pause");
return 0;
}
原创粉丝点击