设计模式合成复用原则

本文探讨了在设计模式中,为何组合通常被优先考虑,通过实例展示了如何在抽象Car类及其子类DaZhong和TLJ中运用组合而非继承。通过People类展示如何使用组合来复用和替换组件,强调了在实际编程中的灵活性和效率。
摘要由CSDN通过智能技术生成

简单来说,继承和组合优先选择组合,所以在设计模式里面并不是所有的模式都要进行继承
在这里插入图片描述
// 合成复用原则.cpp : Defines the entry point for the console application.
//

#include “stdafx.h”
#include
using namespace std;
//抽象类
class AbstractCar
{
public:
virtual void run()=0;
};
//子类
class DaZhong:public AbstractCar
{
public:
virtual void run()
{
cout<<“大众启动ing”<<endl;
}
};
//子类
class TLJ:public AbstractCar
{
public:
virtual void run()
{
cout<<“拖拉机启动ing”<<endl;
}
};
//人类
class People
{
public:
People()
{

}
void setCar(AbstractCar *car)
{
	this->car=car;
}
void DouFeng()
{
	this->car->run();
}
~People()
{
	if(this->car!=NULL)
	{
		delete this->car;
	}
}
AbstractCar *car;

};
void test()
{
People p;
p.setCar(new DaZhong);
p.DouFeng();
}
int main(int argc, char* argv[])
{
test();
printf(“Hello World!\n”);
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值