- 说人话:抽象基类统一接口,并且规定好 事件 运作流程
以实体店买手机为例:
买手机->去实体店->购买手机
.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();
}