一文学会设计模式

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最近在研究设计模式,发现尽管设计模式是针对面向对象语言提出的,但貌似市面上大多数都是基于java给出的例子,C++的例子极少,自己看完李建忠老师的GOF设计模式视频后查阅各种资料并结合自身实践总结如下,希望对大家有所帮助。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"设计模式简介"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"设计模式是主要针对面向对象语言提出的一种设计思想,主要是提高代码可复用性,抵御变化,尽量将变化所带来的影响降到最低。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"面向对象特点"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","content":[{"type":"text","text":"封装:隐藏内部实现"}]}]},{"type":"listitem","content":[{"type":"paragraph","content":[{"type":"text","text":"继承:复用现有的代码"}]}]},{"type":"listitem","content":[{"type":"paragraph","content":[{"type":"text","text":"多态:改写对象的行为"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"面向对象设计原则"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":1,"normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"依赖倒置原则:针对接口编程,依赖于抽象而不依赖于具体,抽象(稳定)不应依赖于实现细节(变化),实现细节应该依赖于抽象,因为稳定态如果依赖于变化态则会变成不稳定态。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"开放封闭原则:对扩展开放,对修改关闭,业务需求是不断变化的,当程序需要扩展的时候,不要去修改原来的代码,而要灵活使用抽象和继承,增加程序的扩展性,使易于维护和升级,类、模块、函数等都是可以扩展的,但是不可修改。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"单一职责原则:一个类只做一件事,一个类应该仅有一个引起它变化的原因,并且变化的方向隐含着类的责任。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"里氏替换原则:子类必须能够替换父类,任何引用基类的地方必须能透明的使用其子类的对象,开放关闭原则的具体实现手段之一。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":5,"align":null,"origin":null},"content":[{"type":"text","text":"接口隔离原则:接口最小化且完备,尽量少public来减少对外交互,只把外部需要的方法暴露出来。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":6,"align":null,"origin":null},"content":[{"type":"text","text":"最少知道原则:一个实体应该尽可能少的与其他实体发生相互作用。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":7,"align":null,"origin":null},"content":[{"type":"text","text":"将变化的点进行封装,做好分界,保持一侧变化,一侧稳定,调用侧永远稳定,被调用测内部可以变化。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":8,"align":null,"origin":null},"content":[{"type":"text","text":"优先使用组合而非继承,继承为白箱操作,而组合为黑箱,继承某种程度上破坏了封装性,而且父类与子类之间耦合度比较高。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":9,"align":null,"origin":null},"content":[{"type":"text","text":"针对接口编程,而非针对实现编程,强调"},{"type":"text","marks":[{"type":"strong"}],"text":"接口标准化"},{"type":"text","text":"。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"小总结: 没有一步到位的设计模式,刚开始编程时不要把太多精力放到设计模式上,需求总是变化的,刚开始着重于实现,一般敏捷开发后为了应对变化重构再决定采取合适的设计模式。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"模板方法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"父类定义算法的骨架,而将一些步骤延迟到子类去实现,使得子类可以复用骨架,并附加特性,以开发框架举例,框架开发人员把框架调用流程定好,而将某些具体的步骤作为虚函数留给子类去重写,话不多说,上代码。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GAME\n#define GAME\n\n#include \n\nclass Game {\n public:\n Game() {}\n\n virtual ~Game() {}\n\n void Run() {\n InitGame();\n StartGame();\n StopGame();\n }\n\n protected:\n virtual void StartGame() { std::cout << \"step 2: start game\" << std::endl; }\n\n private:\n void InitGame() { std::cout << \"step 1: init game\" << std::endl; }\n void StopGame() { std::cout << \"step 3: stop game\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"game.h\"\n\nclass BasketBall : public Game {\n void StartGame() override { std::cout << \"start basketball game\" << std::endl; }\n};"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"game.h\"\n\nclass SocketBall : public Game {\n void StartGame() override { std::cout << \"start socketball game\" << std::endl; }\n};"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"basketball.h\"\n#include \"socketball.h\"\n\nint main() {\n Game game = new BasketBall();\n game->Run();\n delete game;\n Game game2 = new SocketBall();\n game2->Run();\n delete game2;\n return 0;\n}\ng++ test.cc -std=c++11 && ./a.out\n输出:\nstep 1: init game\nstart basketball game\nstep 3: stop game\nstep 1: init game\nstart socketball game\nstep 3: stop game"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"代码很简单,体现的是思想,游戏包含三个步骤,初始化游戏,开始游戏,停止游戏,初始化游戏和停止游戏步骤比较统一,由父类Game定义好,而开始游戏是第二个步骤,可以有打篮球和踢足球,将来也可以有羽毛球,乒乓球等等,每增加一项运动,都可以从Game父类中继承后重写开始游戏这个函数,达到不同的功能,符合"},{"type":"text","marks":[{"type":"strong"}],"text":"模板方法"},{"type":"text","text":"的特性,即"},{"type":"text","marks":[{"type":"strong"}],"text":"如何在确定稳定结构前提下,应对子步骤需求的变化"},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"策略模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一系列的算法,将它们一个个封装,使得他们可以相互替换,一般为了解决多个if-else带来的复杂性,在多种算法相似的情况下,通过策略模式可减少if-else带来的复杂性和难以维护性,一般在项目中发现多个if-else并且预感将来还会在此增加if-else分支,那基本上就需要使用策略模式。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"先举一个不使用策略模式的例子,拿计算来说,下面代码定义了加法操作和减法操作,以后如果需要增加乘法除法等计算,那就需要在枚举里添加新类型,并且增加if-else分支,这违反了开放关闭原则。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"enum class CalOperation {\n add,\n sub\n};\n\nint NoStragegy(CalOperation ope) {\n if (ope == CalOperation::add) {\n std::cout << \"this is add operation\" << std::endl;\n } else if (ope == CalOperation::sub) {\n std::cout << \"this is sub operation\" << std::endl;\n } // 如何将来需要增加乘法或者除法或者其它运算,还需要增加if-else\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下例为使用策略模式,定义一个基类Calculation,包含虚函数operation()。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef CALCULATION\n#define CALCULATION\n\n#include \n\nclass Calculation {\n public:\n Calculation() {}\n\n virtual ~Calculation() {}\n\n virtual void operation() { std::cout << \"base operation\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每增加一种运算,就增加一个继承基类的子类,重写operation()函数。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef ADD\n#define ADD\n\n#include \"calculation.h\"\n\nclass Add : public Calculation {\n void operation() override { std::cout << \"this is add operation\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef SUB\n#define SUB\n\n#include \"calculation.h\"\n\nclass Sub : public Calculation {\n void operation() override { std::cout << \"this is sub operation\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"int Stragegy() {\n Calculation cal = new Add();\n cal->operation();\n delete cal;\n\n Calculation cal2 = new Sub(); // 这里将来都可以用工厂模式改掉,不会违反开放封闭原则\n cal2->operation();\n delete cal2;\n\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"是不是方便了很多,将来如果有乘法除法和其它运算规则,只需要再加一个继承基类的子类即可。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"观察者模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义对象间的一对多关系,当一个对象状态发生改变的时候,其它依赖于它的对象都会得到广播通知并进行自定义动作,通过面向对象技术的多态技术,可以降低这种依赖关系,降低耦合度,上代码."}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef OBSERVER\n#define OBSERVER\n\n#include \n\nclass ObserverBase {\n public:\n ObserverBase() {}\n virtual ~ObserverBase() {}\n\n virtual void Update() {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _OBSERVERFIRSTCHILD\n#define OBSERVERFIRSTCHILD_\n\n#include \"observer.h\"\n\nclass ObserverFirstChild : public ObserverBase {\n void Update() override {\n std::cout << \"first child receive notify\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _OBSERVERSECONDCHILD\n#define OBSERVERSECONDCHILD_\n\n#include \"observer.h\"\n\nclass ObserverSecondChild : public ObserverBase {\n void Update() override {\n std::cout << \"second child receive notify\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \n#include \"observerfirstchild.h\"\n#include \"observersecondchild.h\"\n\nclass NotifyBase {\n public:\n void Add(ObserverBase ob) { observers.emplace_back(ob); };\n\n void Remove(ObserverBase ob) { observers.remove(ob); }\n\n void Notify() {\n for (auto observer : observers) {\n observer->Update();\n }\n }\n\n private:\n std::list observers;\n};\n\nint main() {\n ObserverBase base1 = new ObserverFirstChild();\n ObserverBase *base2 = new ObserverSecondChild();\n\n NotifyBase notify;\n notify.Add(base2);\n notify.Add(base1);\n notify.Notify();\n notify.Remove(base1);\n notify.Notify();\n\n delete base2;\n delete base1;\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过观察者模式可以灵活的控制依赖的对象,动态的增加和删除需要得到通知的对象。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"装饰器模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"动态的给一个对象添加一些额外的职责,扩展一个类的功能,就增加功能来说,使用装饰器模式比单纯的继承子类更加灵活,不一定非要疯狂使用继承方式。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"举个例子,有游戏这个大类,扩展这个类的功能,有打篮球,踢足球,玩lol,玩卡丁车,可以分别定义继承游戏基类的四个子类,但是如果想组合这几个功能呢,一个对象既会打篮球又会玩卡丁车,既会打篮球又会玩lol,再定义几个类继承游戏基类显然不是好的做法,装饰器模式可以很好的解决这个问题,上代码:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先定义一个Game基类"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GAME\n#define GAME\n\n#include \n\nclass Game {\n public:\n Game() {}\n\n virtual ~Game() {}\n\n virtual void Skill() { std::cout << \"game skill\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义卡丁车子类和lol子类"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _CARGAME\n#define CARGAME_\n\n#include \"game.h\"\n\nclass CarGame : public Game {\n public:\n void Skill() override { std::cout << \"car game\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _LOLGAME\n#define LOLGAME_\n\n#include \"game.h\"\n\nclass LolGame : public Game {\n public:\n void Skill() override { std::cout << \"lol game\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"篮球和足球子类也可以像上面一样继承定义,但是如果都像上面一样继承的话不能实现动态扩展功能的需求,所以先定义一个装饰类,之后定义继承这个装饰类的篮球和足球子类。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _DECORATORGAME\n#define DECORATORGAME\n\n#include \"game.h\"\n\nclass DecoratorGame : public Game {\n protected:\n Game game;\n\n public:\n DecoratorGame(Game game) { game = game; }\n\n void Skill() override { game->Skill(); }\n\n virtual ~DecoratorGame() {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef BASKETBALL\n#define BASKETBALL\n\n#include \"decorator_game.h\"\n\nclass BasketBallGame : public DecoratorGame {\n public:\n BasketBallGame(Game *game) : DecoratorGame(game) {}\n\n void Skill() override {\n std::cout << \"basketball game\" << std::endl;\n DecoratorGame::Skill();\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef SOCKETBALL\n#define SOCKETBALL\n\n#include \"decorator_game.h\"\n\nclass SocketBallGame : public DecoratorGame {\n public:\n SocketBallGame(Game *game) : DecoratorGame(game) {}\n\n void Skill() override {\n std::cout << \"socket game\" << std::endl;\n DecoratorGame::Skill();\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最后看使用"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"lolgame.h\"\n#include \"decoratorgame.h\"\n#include \"basketball.h\"\n#include \"cargame.h\"\n#include \"socketball.h\"\n\nint main() {\n Game lol = new LolGame();\n Game car = new CarGame();\n // 一个人既会打篮球又会打LOL可以如下使用\n Game basketballlol = new BasketBallGame(lol);\n basketballlol->Skill();\n std::cout << std::endl;\n // 一个人既会打篮球又会玩卡丁车可以如下使用\n Game basketballcar = new BasketBallGame(car);\n basketballcar->Skill();\n std::cout << std::endl;\n // 一个人既会打篮球又会玩卡丁车又会踢足球可以如下使用\n Game* g = new SocketBallGame(basketballlol);\n g->Skill();\n\n delete lol;\n delete basketballcar;\n delete basketballlol;\n delete g;\n\n return 0;\n}\n// 输出\nbasketball game\nlol game\n\nbasketball game\ncar game\n\nsocket game\nbasketball game\nlol game"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过上例可以看出,使用观察者模式可以动态的扩展类的职责,动态的组合类的各个功能,当看代码时发现一个类既继承了父类同时又持有父类的对象指针,那这基本上就是装饰器模式。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"桥接模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"确定好抽象部分和实现部分,将抽象部分和实现部分分离,使得他们可以独立的变化,实现系统和抽象系统可能各自都会有各自的变化,使用桥接模式可以更加灵活的扩展,方法:用组合代替继承。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"举例:一个图形基类,可以有圆形矩形多边形等等,每个都需要从图形基类中继承出一个子类,但是每个子类还需要画图,画颜色,圆形可能需要黄色黑色白色蓝色等等,矩形也可能需要黄色黑色白色蓝色等等,这种如果单纯的使用继承就不太灵活,可以使用桥接模式,把图形种类当作抽象部分,画颜色当作实现部分,使用组合的方式将抽象部分和实现部分分离,上代码: "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先将实现部分(画图)提取出来,同时多种画图方式从这个基类继承后重写,之后会作为Shape图形类的一个成员变量"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SHAPEDRAWIMPL\n#define SHAPEDRAWIMPL_\n\n#include \n\nclass ShapeDrawImpl {\n public:\n virtual void Draw() = 0;\n\n virtual ~ShapeDrawImpl() {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SHAPEDRAWIMPLRED\n#define SHAPEDRAWIMPLRED\n\n#include \"shapedraw_impl.h\"\n\nclass ShapeDrawImplRed : public ShapeDrawImpl{\n public:\n virtual void Draw() override {\n std::cout << \"draw red\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SHAPEDRAWIMPLBLACK\n#define SHAPEDRAWIMPLBLACK\n\n#include \"shapedraw_impl.h\"\n\nclass ShapeDrawImplBlack : public ShapeDrawImpl{\n public:\n virtual void Draw() override {\n std::cout << \"draw black\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面定义了两种颜色的实现方式,红色和黑色,下面定义图形的类,定义一个图形基类,持有画图实现的句柄,之后定义多个继承图形基类的子类,圆形子类和矩形子类。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef SHAPE\n#define SHAPE\n\n#include \"shapedrawimpl.h\"\n\nclass Shape {\n protected:\n ShapeDrawImpl impl;\n\n public:\n virtual void Update() {}\n Shape(ShapeDrawImpl impl) : impl(impl) {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SHAPECIRCLE\n#define SHAPECIRCLE_\n\n#include \"shape.h\"\n\nclass ShapeCircle : public Shape {\npublic:\n void Update() override {\n std::cout << \"circle shape update\" << std::endl; \n impl->Draw();\n }\n\n ShapeCircle(ShapeDrawImpl *imp) : Shape(imp) {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SHAPERECTANGLE\n#define SHAPERECTANGLE_\n\n#include \"shape.h\"\n\nclass ShapeRectangle : public Shape {\n public:\n void Update() override {\n std::cout << \"rectangle shape update\" << std::endl;\n impl->Draw();\n }\n\n ShapeRectangle(ShapeDrawImpl *imp) : Shape(imp) {}\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"shapecircle.h\"\n#include \"shaperectangle.h\"\n#include \"shapedrawimplblack.h\"\n#include \"shapedrawimplred.h\"\n\nint main() {\n ShapeDrawImpl impl = new ShapeDrawImplBlack();\n Shape circle = new ShapeCircle(impl);\n circle->Update();\n\n delete impl;\n delete circle;\n \n return 0;\n}\n输出:\ncircle shape update\ndraw black"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过桥接模式可以更好的应对变化,应对抽象和实现的多种组合变化。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"工厂模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"工厂模式属于创建型模式,主要用于创建对象时不向外部暴露创建逻辑,通过一个共同的接口指向新创建的对象,通过面向对象的多态,将创建对象的工作延迟到子类执行,由子类决定实例化哪个对象。用于隔离对象使用者与其具体类型之间的耦合关系,当具体类型经常变化时,可以考虑使用工厂模式。有一个类型的抽象基类,同时又有很多继承该抽象基类的具体类型,我们做的就是使其依赖于抽象而不依赖于具体,实现方式是创建一个工厂基类,在为每个具体类型定义一个可以创建其相应对象的工厂,每一个具体类对应一个具体工厂,工厂类继承自工厂基类,通过工厂基类的多态性就可以决定创建什么类型的对象。上代码:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GAME\n#define GAME\n\n#include \n\nclass Game {\n public:\n Game() {}\n virtual ~Game() {}\n\n virtual void Play() {\n std::cout << \"play game\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef BASKETBALL\n#define BASKETBALL\n\n#include \"game.h\"\n\nclass BasketBall : public Game {\n void Play() override { std::cout << \"play basketball\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef SOCKETBALL\n#define SOCKETBALL\n\n#include \"game.h\"\n\nclass SocketBall : public Game {\n void Play() override { std::cout << \"play socketball\" << std::endl; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以通过游戏工厂选择创建不同游戏类型的对象"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _GAMEFACTORY\n#define GAMEFACTORY_\n\n#include \"game.h\"\n\nclass GameFactory {\n public:\n GameFactory() {}\n virtual ~GameFactory() {}\n\n virtual Game* CreateGame() = 0;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _BASKETBALLFACTORY\n#define BASKETBALLFACTORY\n\n#include \"gamefactory.h\"\n#include \"basketball.h\"\n\nclass BasketBallFactory : public GameFactory {\n public:\n Game* CreateGame() override{\n return new BasketBall();\n };\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _SOCKETBALLFACTORY\n#define SOCKETBALLFACTORY\n\n#include \"gamefactory.h\"\n#include \"socketball.h\"\n\nclass SocketBallFactory : public GameFactory {\n public:\n Game* CreateGame() override{\n return new SocketBall();\n };\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"basketballfactory.h\"\n#include \"socketballfactory.h\"\n\nint main() {\n GameFactory factory = new BasketBallFactory();\n Game game = factory->CreateGame();\n game->Play();\n\n delete factory;\n delete game;\n\n factory = new SocketBallFactory();\n game = factory->CreateGame();\n game->Play();\n\n delete factory;\n delete game;\n\n return 0;\n}\n输出:\nplay basketball\nplay socketball"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当有新类型增加时,需要添加一个具体类和一个相应的创建工厂,尽管减少了耦合度,但是其实还是比较麻烦的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"抽象工厂方法模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"和工厂方法模式类似,不做过多介绍,说一下定义,抽象工厂方法模式主要提供一个接口,让该接口负责创建多系列“相关或相互的对象”,无需指定具体的类,系列对象指的是某一特定系列下的对象间有相互依赖或相互作用的关系,不同系列的对象之间不能相互依赖,如果没有多系列对象创建的需求变化,没必要使用"},{"type":"text","marks":[{"type":"strong"}],"text":"抽象工厂方法"},{"type":"text","text":"模式,使用"},{"type":"text","marks":[{"type":"strong"}],"text":"简单工厂方法"},{"type":"text","text":"模式就可以,拿上一个举例继续说,游戏类型是一个系列,我们有了一个游戏类型的工厂,以后可能会再加入娱乐圈类型的一个系列,那就在做一个娱乐圈类型的系列工厂,以后可能还有文艺类型的系列,那就再加一个文艺类型的系列工厂,这就有了三个系列的工厂,所以就可以在这三类工厂的基础上再抽象出一个抽象的超级工厂,根据不同需求选择实例化哪一个系列的具体工厂,再创建具体工厂下的具体类型的对象。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"原型模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用于创建重复的对象,定义一个clone接口,通过调用clone接口创建出与原来类型相同的对象,上代码:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GAME\n#define GAME\n\n#include \n\nclass Game {\n public:\n virtual Game* clone() = 0;\n\n virtual void Play() = 0;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef BASKETBALL\n#define BASKETBALL\n\n#include \"game.h\"\n\nclass BasketBall : public Game {\n virtual Game* clone() override {\n return new BasketBall();\n }\n\n virtual void Play() override {\n std::cout << \"basketball\" << std::endl;\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"basketball.h\"\n\nint main() {\n Game game = new BasketBall();\n game->Play();\n Game newgame = game->clone();\n newgame->Play();\n \n delete game;\n delete new_game;\n\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"单纯看game不知道它是什么类型,它可能是篮球游戏也可能是足球游戏等,如果想创建一个与它相同类型的对象就可以使用原型模式其实就是实现一个clone接口,如果一个对象的拷贝构造函数比较复杂而自己不想使用拷贝构造的方式创建对象也可以使用原型模式,使用方式见上例。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"建造者模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用于构建一个复杂的大的对象,一个复杂的对象通常需要一步步才可以构建完成,建造者模式强调的是一步步创建对象,并通过相同的构建过程可以获得不同的结果对象,一般来说建造者对象不是直接返回的,与抽象工厂方法区别是抽象工厂方法用于创建多个系列的对象,而建造者模式强调一步步构建对象,并且构建步骤固定,举例:想要构建一个老师类的对象,老师有第一技能和第二技能,第一技能是数学就代表是数学老师,第一技能是英语就代表是语文老师,构造一个老师对象需要先设定老师的第一技能再设定老师的第二技能,强调一步步设定技能,将这一步步的构建过程可以抽象出建造者模式。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先定义老师类"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef TEACHER\n#define TEACHER\n\n#include \n#include \n\nclass Teacher {\n private:\n std::string firstskill;\n std::string secondskill;\n\n public:\n void SetFirstSkill(const std::string& skill) { this->firstskill = skill; }\n\n void SetSecondSkill(const std::string& skill) { this->secondskill = skill; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个老师的抽象构建器,再根据具体老师继承出具体的老师构建器"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _TEACHERABSTRACTBUILDER\n#define TEACHERABSTRACTBUILDER_\n\n#include \"teacher.h\"\n\nclass TeacherAbstractBuilder {\n public:\n TeacherAbstractBuilder() {}\n virtual ~TeacherAbstractBuilder() {}\n\n virtual void BuildFirstSkill() = 0;\n virtual void BuildSecondSkill() = 0;\n\n virtual Teacher* GetTeacher() = 0;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _MATHTEACHERBUILDER\n#define MATHTEACHERBUILDER\n\n#include \"teacherabstractbuilder.h\"\n\nclass MathTeacherBuilder : public TeacherAbstractBuilder {\n public:\n MathTeacherBuilder() { this->teacher = new Teacher(); }\n\n ~MathTeacherBuilder() { delete this->teacher; }\n\n Teacher GetTeacher() { return this->teacher; }\n\n void BuildFirstSkill() { this->teacher->SetFirstSkill(\"math\"); }\n\n void BuildSecondSkill() { this->teacher->SetSecondSkill(\"english\"); }\n\n private:\n Teacher teacher_;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _ENGLISHTEACHERBUILDER\n#define ENGLISHTEACHERBUILDER\n\n#include \"teacherabstractbuilder.h\"\n\nclass EnglishTeacherBuilder : public TeacherAbstractBuilder {\n public:\n EnglishTeacherBuilder() { this->teacher = new Teacher(); }\n\n ~EnglishTeacherBuilder() { delete this->teacher; }\n\n Teacher GetTeacher() { return this->teacher; }\n\n void BuildFirstSkill() { this->teacher->SetFirstSkill(\"english\"); }\n\n void BuildSecondSkill() { this->teacher->SetSecondSkill(\"math\"); }\n\n private:\n Teacher teacher_;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个稳定的Director类,由它根据具体的老师构建器决定构建哪一个老师"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef DIRECTOR\n#define DIRECTOR\n\n#include \"teacherabstractbuilder.h\"\n\nclass Director {\n public:\n Director(TeacherAbstractBuilder builder) { this->builder = builder; }\n\n ~Director() {}\n\n void Create() {\n this->builder->BuildFirstSkill();\n this->builder->BuildSecondSkill();\n }\n\n private:\n TeacherAbstractBuilder builder;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"使用方法如下:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"director.h\"\n#include \"englishteacherbuilder.h\"\n#include \"mathteacherbuilder.h\"\n\nint main() {\n TeacherAbstractBuilder builder = new MathTeacherBuilder();\n Director director = new Director(builder);\n delete builder;\n delete director;\n\n builder = new EnglishTeacherBuilder();\n director = new Director(builder);\n delete builder;\n delete director;\n\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过Director利用不同的具体构建器都采用相同的步骤一步步构建出不同的具体的老师类对象。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"单例模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不多说了,网上太多了,列一段单例的代码:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"static SingleTon& GetInstance() {\n static SingleTon t;\n return t;\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"享元模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过共享技术有效支持大量细粒度的对象,主要解决面向对象代价问题,通过共享有效降低创建的对象个数,类似于对象池。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"举例:篮球分多种颜色,我想要蓝色的篮球想要红色的篮球这就需要创建两个对象,当我再想要一个蓝色的篮球如果能够继续使用之前的那个对象就更好,通过享元模式可以做到。"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef BASKETBALL\n#define BASKETBALL\n\n#include \n#include \n\nclass BasketBall {\n public:\n BasketBall(const std::string& color) : color(color) {}\n ~BasketBall() {}\n\n private:\n std::string color;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _BASKETBALLFACTORY\n#define BASKETBALLFACTORY\n\n#include \n#include \"basketball.h\"\n\nclass BasketballFactory {\n private:\n std::unorderedmap<:string basketball=""> map;\n\n public:\n BasketBall GetBasketBallWithColor(const std::string& color) {\n if (map.find(color) == map.end()) {\n BasketBall* p = new BasketBall(color);\n map[color] = p;\n return p;\n } else {\n return map[color];\n }\n }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"BasketballFactory.h\"\n\nint main() {\n BasketballFactory factory;\n BasketBall whiteball1 = factory.GetBasketBallWithColor(\"white\");\n BasketBall blackball1 = factory.GetBasketBallWithColor(\"black\");\n BasketBall whiteball2 = factory.GetBasketBallWithColor(\"white\");\n BasketBall blackball2 = factory.GetBasketBallWithColor(\"black\");\n std::cout << whiteball1 << std::endl;\n std::cout << whiteball2 << std::endl;\n std::cout << blackball1 << std::endl;\n std::cout << blackball2 << std::endl;\n // remember to delete\n return 0;\n}\n输出:\n0x7fffe4984e70\n0x7fffe4984e70\n0x7fffe4984f00\n0x7fffe4984f00"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"外观模式(Facade Pattern)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"感觉外观模式没啥特别的,感觉就是做好功能之间边界的划分,做好封装,弄清楚哪部分是稳定的,哪部分是变化的,对外稳定松耦合,对内迭代变化高内聚,子系统的内部外部要做好解耦,为子系统的一组接口提供一个稳定一致的(界面),子系统中的任何变化都不会影响这个(界面)的变化。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"代理模式(Proxy Pattern)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为其它对象提供一种代理以控制这个对象的访问,一般对于比较大的对象访问比较困难或者或带来很多麻烦,例如裸指针的使用,所以一般使用智能指针来控制裸指针,使用智能指针也是一种代理模式,举例:A喜欢B想送给B礼物,但是却不认识B,而C却认识B,所以可以把C作为A的代理去送给B礼物,代码:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GIRL\n#define GIRL\n\n#include \n#include \n\nclass Girl {\n private:\n std::string name;\n\n public:\n Girl(const std::string &name) : name(name) {}\n\n std::string GetName() const noexcept { return name_; }\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef GIFT\n#define GIFT\n\n#include \"girl.h\"\n\nclass Gift {\n public:\n virtual void GiveGift() = 0;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#ifndef _GIFTPROXY\n#define GIFTPROXY\n\n#include \"gift.h\"\n#include \"girl.h\"\n\nclass GiftProxy : public Gift {\n public:\n GiftProxy(Girl girl) : girl(girl) {}\n\n void GiveGift() override { std::cout << \"send \" << girl.GetName() << \" gift\" << std::endl; }\n\n private:\n Girl girl;\n};\n\n#endif"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \"gift_proxy.h\"\n\nint main() {\n Girl lili(\"lili\");\n GiftProxy proxy(lili);\n proxy.GiveGift();\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如上述代码,通过代理模式就可以给丽丽送礼物。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"适配器模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"太常见了,每个人都会用,两个不兼容的接口之间的桥梁,就像耳机转换头,充电器转换头等等都是适配器模式,将一个类的接口转换为客户希望的另一种接口的形式,使得原本由于接口不兼容而不能一起工作的类可以一起工作。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"中介模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"使用一个中介对象来封装一系列的对象交互,当多个对象间互相引用且操作比较复杂时可以考虑使用中介模式。如下图所示:左侧五个对象互相依赖,通过中介这个桥梁就可以减少这个依赖。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"![d320c85de4434586e5fb5931742e6cd.jpg](https://upload-images.jianshu.io/upload_images/3725930-0dc4b653116db321.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/440)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"状态模式"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当一个对象的行为依赖于它的状态并且其有很多种状态而且将来还会有更多状态时,如果使用简单的if-else来增加新状态就违反了面向对象的开闭原则,这时可以考虑使用状态模式,将具体的状态做出一个抽象类,也类似于工厂模式,将具体的状态分散于各个子类中,避免了更多的if-else分支,上代码:"}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"#include \nusing namespace std;\n\nclass Context;\nclass State {\n public:\n virtual void Handle(Context *context) = 0;\n};\n\nclass Context {\n public:\n Context(State *state) : state_(state) {}\n void Request() {\n if (state_) {\n state_->Handle(this);\n }\n }\n void ChangeState(State *pState) { state_ = pState; }\n private:\n State *state_;\n};\n\nclass ConcreteStateA : public State {\n public:\n void Handle(Context *context) override { cout << \"I am state a\" << endl; }\n};\n\nclass ConcreteStateB : public State {\n public:\n void Handle(Context *context) override { cout << \"I am state b\" << endl; }\n};\n\nint main() {\n State *state_a = new ConcreteStateA();\n State *state_b = new ConcreteStateB();\n Context *context = new Context(state_a);\n context->Request();\n context->ChangeState(state_b);\n context->Request();\n\n delete context;\n delete state_b;\n delete state_a;\n\n return 0;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章