學習設計模式的思想

來源:互聯網
上載者:User

標籤:設計模式思想   簡單原廠模式   

我實現設計模式是基於C++語言的;

1、設計模式:主要是研究類與類之間的關係;

2、設計模式的基石:利用C++中的多態技術;

3、開閉原則:通過添加代碼,而不是修改代碼,完成功能的修改與擴充;

4、依賴倒置原則:產品和架構都向抽象層靠攏;

5、簡單工產模式:不屬於23種設計模式,將產品的建立都放到一個類(具體的工廠類)中去生產;

6、設計模式就是一種規定的形式,是一種套路,關鍵是理解思想;


7、簡單原廠模式

  簡單原廠模式:建立型模式/靜態Factory 方法模式,不屬於23種設計模式,
  就是實實在在的構造一個工廠類(高內聚,新增添的話,必須修改原有代碼,而不是擴充原有代碼),不易擴充;
  作用:用一個類去建立其它類,但都有一個介面(面向抽象類別編程);

  (1)、代碼實現

#include<iostream>#include<string.h>using namespace std;class Fruit{    public:        virtual void getFruit() = 0;    private:};class Banana : public Fruit{    public:        virtual void getFruit(){            cout<<"我是香蕉......"<<endl;        }       private:};class Apple : public Fruit{    public:        virtual void getFruit(){            cout<<"我是蘋果......"<<endl;        }    private:};class Factory{    public:        Fruit *create(const char *p){            if(strcmp(p, "banana") == 0){                return new Banana;            }else if(strcmp(p, "apple") == 0){                return new Apple;            }else{                cout<<"不支援"<<endl;            }        }    private:};int main(void){    Factory *f = new Factory;    Fruit *fruit = NULL;    //工廠生產香蕉    fruit = f->create("banana");    fruit->getFruit();      //工廠生產蘋果    fruit = f->create("apple");    fruit->getFruit();    delete f;    return 0;}

  (2)、運行結果

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M01/8B/F6/wKiom1hc-_iB929BAABD1HqoPTA952.png-wh_500x0-wm_3-wmp_4-s_536662010.png" title="QQ20161223182644.png" alt="wKiom1hc-_iB929BAABD1HqoPTA952.png-wh_50" />


本文出自 “wait0804” 部落格,請務必保留此出處http://wait0804.blog.51cto.com/11586096/1885612

學習設計模式的思想

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.