Design Pattern Command 命令設計模式

來源:互聯網
上載者:User

標籤:

本設計模式就是利用不同的類包起不同的命令,達到使用什麼命令就實現什麼操作。

也可以進一步利用map和自己喜歡的命令詞對接起來。

一個執行類實際上已經包含了所有需要的操作了,如:

class SuperMaker{public:string makeCar(){return "Car";}string makePlane(){return "Plane";}};

這裡有兩個命令,下面要做的就是使用不同的類把需要的命令包含起來。

class Command{protected:SuperMaker *sm;public:virtual void exeCmd() = 0;};class MakeCarCmd : public Command{public:MakeCarCmd(SuperMaker *s){sm = s;}void exeCmd(){cout<<sm->makeCar()<<std::endl;}};class MakePlaneCmd : public Command{public:MakePlaneCmd(SuperMaker *s){sm = s;}void exeCmd(){cout<<sm->makePlane()<<std::endl;}};

這裡的MakeCarCmd和MakePlaneCmd這兩個類分別實現不同的命令。使用不同的類就能實現不同的操作。

具體要如何?怎麼使用這些類(命令),那麼可以自己定義,如可以使用map和有意義的字串對應起來,也可以使用一個類包這些命令再次包含起來等操作。


全部代碼:

#include <iostream>#include <string>using std::string;using std::cout;class SuperMaker{public:string makeCar(){return "Car";}string makePlane(){return "Plane";}};class Command{protected:SuperMaker *sm;public:virtual void exeCmd() = 0;};class MakeCarCmd : public Command{public:MakeCarCmd(SuperMaker *s){sm = s;}void exeCmd(){cout<<sm->makeCar()<<std::endl;}};class MakePlaneCmd : public Command{public:MakePlaneCmd(SuperMaker *s){sm = s;}void exeCmd(){cout<<sm->makePlane()<<std::endl;}};int main(){SuperMaker suMa;MakeCarCmd mcc(&suMa);Command *cmdCar = &mcc;MakePlaneCmd mpc(&suMa);Command *cmdPlane = &mpc;cmdCar->exeCmd();cmdPlane->exeCmd();return 0;}

運行:




Design Pattern Command 命令設計模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.