1、状态模式的提出
在组件功能开发过程中,某些对象的状态经常面临变化,不同的状态,其对象的操作行为不同。比如根据状态写的if else条件情况,且这种条件变化是经常变化的,这样的代码不易维护。可以使用状态模式解决这类问题。状态模式是将状态值抽象成一个基类,将不同状态下的操作,封装成基类中的虚函数,使用者可以依赖抽象的基类来进行功能开发。
2、需求描述
一年有不同节日,不同的节日穿不同的衣服,吃不同的食物。节日可能会随着人们的生活习俗不断地增加。设计一个根据不同地节日,返回对应穿着和食物方面的功能代码。
3、状态模式的代码实现
(1)UML图如下:
(2)代码实现如下:
#include <iostream>
class AbsFestival
{
public:virtual ~AbsFestival(){};virtual void Eat()=0;virtual void Wear()=0;
};class FestivalA:public AbsFestival
{
public:static FestivalA* getInstance(){static FestivalA obj;return &obj;};virtual void Eat()override{std::cout << "FestivalA Eat" << std::endl;}virtual void Wear()override{std::cout << "FestivalA Wear" << std::endl;};
};class FestivalB:public AbsFestival
{
public:static FestivalB* getInstance(){static FestivalB obj;return &obj;};virtual void Eat()override{std::cout << "FestivalB Eat" << std::endl;}virtual void Wear()override{std::cout << "FestivalB Wear" << std::endl;};
};class FestivalC:public AbsFestival
{
public:static FestivalC* getInstance(){static FestivalC obj;return &obj;};virtual void Eat()override{std::cout << "FestivalC Eat" << std::endl;}virtual void Wear()override{std::cout << "FestivalC Wear" << std::endl;};
};class FestivalD:public AbsFestival
{
public:virtual void Eat()override{std::cout << "FestivalD Eat" << std::endl;}virtual void Wear()override{std::cout << "FestivalD Wear" << std::endl;};
};class Client
{
protected:AbsFestival *time;
public:void SetTime(AbsFestival* p){time = p;}void DoWork(){time->Eat();time->Wear();}
};int main()
{Client useObj;FestivalA festivalA;useObj.SetTime(festivalA.getInstance());useObj.DoWork();FestivalB festivalB;useObj.SetTime(festivalB.getInstance());useObj.DoWork();FestivalC festivalC;useObj.SetTime(festivalC.getInstance());useObj.DoWork();FestivalD* festivalD = new FestivalD();useObj.SetTime(festivalD);useObj.DoWork();delete festivalD;festivalD = nullptr;return 0;
}
程序运行结果如下: