模板模式(C++)

  • 说人话:抽象基类统一接口,并且规定好 事件 运作流程

以实体店买手机为例:

买手机->去实体店->购买手机

.h

class AbstractBuyPhone
{
public:
	virtual void buyPhone() = 0;
	virtual void goToRealShop() = 0;
	virtual void buyPhoneSuccess() = 0;
	//固化流程
	void process();
};

class BuyApplePhone :public AbstractBuyPhone
{
public:
	virtual void buyPhone() override;
	virtual void goToRealShop() override;
	virtual void buyPhoneSuccess() override;
};

class BuyXiaoMiPhone :public AbstractBuyPhone
{
public:
	virtual void buyPhone() override;
	virtual void goToRealShop() override;
	virtual void buyPhoneSuccess() override;
};

.cpp

int main()
{
	//什么情况不能用抽象基类指针 承接 子类指针
	AbstractBuyPhone* BAP = new BuyApplePhone();
	AbstractBuyPhone* BXP = new BuyXiaoMiPhone;
	BAP->process();
	BXP->process();
	delete BAP;
	delete BXP;
	BAP = nullptr;
	BXP = nullptr;

	return 0;
}
void BuyApplePhone::buyPhone()
{
	cout << "准备买苹果手机!" << endl;
}

void BuyApplePhone::goToRealShop()
{
	cout << "去苹果直营店!" << endl;
}

void BuyApplePhone::buyPhoneSuccess()
{
	cout << "买了苹果手机!" << endl;
}

void BuyXiaoMiPhone::buyPhone()
{
	cout << "准备买小米手机!" << endl;
}

void BuyXiaoMiPhone::goToRealShop()
{
	cout << "去小米直营店!" << endl;
}

void BuyXiaoMiPhone::buyPhoneSuccess()
{
	cout << "买了小米手机!" << endl;
}

void AbstractBuyPhone::process()
{
	buyPhone();
	goToRealShop();
	buyPhoneSuccess();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值