未经授权,禁止转载!创作不易,尊重原创!~~
在软件构建过程中,某些对象的状态如果改变,其行为也会随之而发生变化,比如文档处于只读状态,其支持的行为和读写状态支持的行为就可能完全不同。 如何在运行时根据对象的状态来透明地更改对象的行为?而不是为对象操作和状态转化之间引入紧耦合?
允许一个对象在其内部状态改变时改变它的行为。从而使对象看起来似乎修改了其行为。 把《设计模式》GoF
王者荣耀这款游戏,在排位赛模式下,bp的方式是和段位挂钩的。砖石以下不需要ban英雄,砖石以上王者以下有两个ban的名额,王者以上有四个ban的名额。就是说段位不一样,进行同样的游戏,bp规则也是不一样的。对战过程中也有类似的情况,巅峰赛会屏蔽召唤师的id。 这里的段位就对应上面的状态。
// rank.h #include<iostream> class Rank { public: Rank* rank_next_; virtual void BanPick() = 0; virtual void Battle() = 0; virtual std::string name() = 0; // // at new Season // virtual void ReceiveAward() = 0; // virtual void SuccessionRank() = 0; }; class GoldRank : public Rank { private: GoldRank() {} public: static Rank* rank_; static Rank* getInstance(); virtual void BanPick(); virtual void Battle(); std::string name() {return "gold";} }; class DiamondRank : public Rank { private: DiamondRank() {} public: static Rank* rank_; static Rank* getInstance(); virtual void BanPick(); virtual void Battle(); std::string name() {return "diamond";} }; class KingRank : public Rank { private: KingRank() {} public: static Rank* rank_; static Rank* getInstance(); virtual void BanPick(); virtual void Battle(); std::string name() {return "king";} }; // rank.cc // #include<iostream> #include "rank.h" Rank* GoldRank::rank_ = nullptr; Rank* DiamondRank::rank_ = nullptr; Rank* KingRank::rank_ = nullptr; Rank* GoldRank::getInstance() { if (rank_ == nullptr) { rank_ = new GoldRank(); } return rank_; } void GoldRank::BanPick() { std::cout << "ban 0 heros" << std::endl; } void GoldRank::Battle() { std::cout << "show nick name" << std::endl; if (1/*victory*/) { rank_next_ = DiamondRank::getInstance(); } } Rank* DiamondRank::getInstance() { if (rank_ == nullptr) { rank_ = new DiamondRank(); } return rank_; } void DiamondRank::BanPick() { std::cout << "ban 2 heros" << std::endl; } void DiamondRank::Battle() { std::cout << "show nick name" << std::endl; if (1/*victory*/) { rank_next_ = KingRank::getInstance(); } } Rank* KingRank::getInstance() { if (rank_ == nullptr) { rank_ = new KingRank(); } return rank_; } void KingRank::BanPick() { std::cout << "ban 4 heros" << std::endl; } void KingRank::Battle() { std::cout << "show no nick name" << std::endl; if (1/*victory*/) { rank_next_ = GoldRank::getInstance(); } } //main.cc #include<iostream> #include"rank.h" void Play() { Rank* rank = GoldRank::getInstance(); for (int i=0; i <=10; i++) { std::cout << rank->name() << std::endl; rank->BanPick(); rank->Battle(); rank = rank->rank_next_; } } int main() { Play(); return 0; }