zoukankan      html  css  js  c++  java
  • 23 种c++设计模式

    创建型模式

    单例模式 (Singleton)

    名称:Singleton(单件模式);

    意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点;

    适用环境

    • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时;
    • 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

    C++实现代码

     1 class Singleton {
     2 public:
     3     static Singleton* Instance();
     4 protected:
     5     Singleton(){}
     6 private:
     7     static Singleton* _instance;
     8 };
     9 
    10 Singleton* Singleton::_instance = 0;
    11 
    12 Singleton* Singleton::Instance () {
    13     if (_instance == 0) {
    14         _instance = new Singleton;
    15     }
    16     return _instance;
    17 }

    工厂方法模式 (Factory Method)

    名称:Factory Method(工厂模式)

    意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。

    适用环境

    • 当一个类不知道它所必须创建的对象的类的时候;
    • 当一个类希望由它的子类来指定它所创建的对象的时候;
    • 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一 个帮助子类;
    • 是代理者这一信息局部化的时候。

      简单工厂 VS 工厂方法

      简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。

      工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现具体产品,工厂 方法把简单工厂的内部逻辑判断移到了客户端代码来进行。想要加功能,本来是 改工厂类的,而现在是修改客户端。

      C++实现

       1 class Product {};
       2 
       3 class ConcreteProduct : public Product
       4 {
       5 public:
       6     ConcreteProduct()
       7     {
       8         cout<<"ConcreteProduct"<<endl;
       9     }
      10 };
      11 
      12 class ConcreteProduct2 : public Product
      13 {
      14 public:
      15     ConcreteProduct2()
      16     {
      17         cout<<"ConcreteProduct2"<<endl;
      18     }
      19 };
      20 
      21 class Creator
      22 {
      23 public:
      24     virtual Product * FactoryMethod()=0;
      25 };
      26 
      27 class ConcreteCreator : public Creator
      28 {
      29 public:
      30     Product * FactoryMethod()
      31     {
      32         return new ConcreteProduct;
      33     }
      34 };
      35 
      36 class ConcreteCreator2 : public Creator
      37 {
      38 public:
      39     Product * FactoryMethod()
      40     {
      41         return new ConcreteProduct2;
      42     }
      43 };
      44 
      45 int main()
      46 {
      47     Product *product;
      48     bool flag = false; //逻辑判断
      49 
      50     if(flag)
      51     {
      52         ConcreteCreator concreteCreator;
      53         product = concreteCreator.FactoryMethod();
      54     }
      55     else
      56     {
      57        ConcreteCreator2 concreteCreator;
      58        product = concreteCreator.FactoryMethod();
      59     }
      60 }

      运行结果

      ConcreteProduct2

    抽象工厂模式 (Abstract Factoy)

    建造者模式 (Buidler)

    名称:Builder(生成器模式)

    意图:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不 同的表示。

    适用环境

    • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时;
    • 当构造过程必须允许被构造的对象有不同的表示时。

    建造者模式主要用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常 是稳定的,但对象内部的构建通常面临着复杂的变化。

    C++实现

      1 #include <iostream>
      2 #include <vector>
      3 #include <string>
      4 using namespace std;
      5 
      6 class Product
      7 {
      8 public:
      9     void Add(string part)
     10     {
     11         parts.push_back(part);
     12     }
     13 
     14     void show()
     15     {
     16         cout<<"--- Product builder ---"<<endl;
     17         for(vector<string>::iterator iter = parts.begin(); iter != parts.end(); ++iter)
     18             cout<<*iter<<endl;
     19     }
     20 
     21     private:
     22         vector<string> parts;
     23 };
     24 
     25 
     26 class Builder
     27 {
     28 public:
     29     virtual void BuilderPartA()=0;
     30     virtual void BuilderPartB()=0;
     31     virtual Product * GetResult()=0;
     32 };
     33 
     34 class ConcreteBuilder1 : public Builder
     35 {
     36 public:
     37     ConcreteBuilder1()
     38     {
     39         product = new Product;
     40     }
     41 
     42     void BuilderPartA()
     43     {
     44         product->Add("Part A");
     45     }
     46 
     47     void BuilderPartB()
     48     {
     49         product->Add("Part B");
     50     }
     51 
     52     Product * GetResult()
     53     {
     54         return product;
     55     }
     56 
     57 private:
     58     Product *product;
     59 };
     60 
     61 class ConcreteBuilder2 : public Builder
     62 {
     63 public:
     64     ConcreteBuilder2()
     65     {
     66         product = new Product;
     67     }
     68 
     69     void BuilderPartA()
     70     {
     71         product->Add("Part X");
     72     }
     73 
     74     void BuilderPartB()
     75     {
     76         product->Add("Part Y");
     77     }
     78 
     79     Product * GetResult()
     80     {
     81         return product;
     82     }
     83 
     84 private:
     85     Product *product;
     86 };
     87 
     88 class Director
     89 {
     90 public:
     91     void Construct(Builder *builder)
     92     {
     93         builder->BuilderPartA();
     94         builder->BuilderPartB();
     95     }
     96 };
     97 
     98 int main()
     99 {
    100     Director *director = new Director;
    101     Builder *b1 = new ConcreteBuilder1;
    102     Builder *b2 = new ConcreteBuilder2;
    103 
    104     director->Construct(b1);
    105     Product *p1 = b1->GetResult();
    106     p1->show();
    107 
    108     director->Construct(b2);
    109     Product *p2 = b2->GetResult();
    110     p2->show();
    111 }

    运行结果

    --- Product builder ---
    Part A
    Part B
    --- Product builder ---
    Part X
    Part Y

    原型模式 (Prototype)

    名称:Prototype(原型模式)

    意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

    适用环境

    • 当一个系统应该独立于它的产品创建、构成和表示时,要使用Prototype模式;
    • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者为了避免创建一个与产品类层次平行的工厂类层次时;或者 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们;
    • 可能比每次用合适的状态手工实例化该类更方便一些。

    原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何 创建的细节。

    C++实现

    View Code
      1 class Prototype
      2 {
      3 public:
      4     virtual Prototype * Clone()=0;
      5 };
      6 
      7 
      8 class Object : public Prototype
      9 {
     10 public:
     11     Object(){}
     12 
     13     Object(int m)
     14     {
     15         n = m;
     16     }
     17 
     18     Object(Object &object)
     19     {
     20         SetValue(object.GetValue());
     21     }
     22 
     23     void SetValue(int n)
     24     {
     25         this->n = n;
     26     }
     27 
     28     int GetValue()
     29     {
     30         return n;
     31     }
     32 
     33     Prototype * Clone()
     34     {
     35         return new Object(*this);
     36     }
     37 
     38     void show()
     39     {
     40         cout<<n<<endl;
     41     }
     42 
     43 private:
     44     int n;
     45 };
     46 
     47 class ConcretePrototype1 : public Prototype
     48 {
     49 public:
     50     ConcretePrototype1(){}
     51 
     52     ConcretePrototype1(Object *obj)
     53     {
     54         SetObject(obj);
     55     }
     56 
     57     ConcretePrototype1(ConcretePrototype1 &concretePrototype1)
     58     {
     59         //SetObject(concretePrototype1.GetObject());      //浅拷贝
     60         SetObject((Object *)(concretePrototype1.GetObject()->Clone())); //深拷贝
     61     }
     62 
     63     Prototype * Clone()
     64     {
     65         return new ConcretePrototype1(*this);
     66     }
     67 
     68     void SetValue(int n)
     69     {
     70         object->SetValue(n);
     71     }
     72 
     73     void show()
     74     {
     75         object->show();
     76     }
     77 
     78     void SetObject(Object *obj)
     79     {
     80         object = obj;
     81     }
     82 
     83     Object * GetObject()
     84     {
     85         return object;
     86     }
     87 
     88 private:
     89     Object *object;
     90 };
     91 
     92 int main()
     93 {
     94 /*
     95     ConcretePrototype1 concretePrototype1(new Object(1));
     96     //concretePrototype1.SetObject(new Object(10));
     97     ConcretePrototype1 concretePrototype2 = *(ConcretePrototype1 *)concretePrototype1.Clone();
     98     concretePrototype1.show();
     99     concretePrototype2.show();
    100 
    101     concretePrototype1.SetValue(2);
    102     concretePrototype1.show();
    103     concretePrototype2.show();
    104 */
    105     Prototype *prototype = new ConcretePrototype1(new Object(1));
    106     ConcretePrototype1 * prototype1 = (ConcretePrototype1 *)prototype;
    107     //prototype1->SetObject(new Object(10));
    108     ConcretePrototype1 * prototype2 = (ConcretePrototype1 *)prototype->Clone();
    109     prototype1->show();
    110     prototype2->show();
    111 
    112     prototype1->SetValue(2);
    113     prototype1->show();
    114     prototype2->show();
    115 }

    浅拷贝运行结果

    1
    1
    2
    2
    深拷贝运行结果
    1
    1
    2
    1

    结构型模式

    适配器模式 (Adapter)

    名称:Adapter(适配器模式);

    意图:将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

    适用环境

    • 你想使用一个已经存在的类,而它的接口不符合你的需求;
    • 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作;
    • (仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。

    C++实现代码

    View Code
     1 class Target
     2 {
     3 public:
     4     //virtual void Request()=0;
     5     virtual void Request()
     6     {
     7         cout<<"Common request."<<endl;
     8     }
     9 };
    10 
    11 class Adaptee
    12 {
    13 public:
    14     void SpecificRequest()
    15     {
    16        cout<<"Specific request."<<endl;
    17     }
    18 };
    19 
    20 class Adapter : Target
    21 {
    22 public:
    23     Adapter()
    24     {
    25        adaptee = new Adaptee;
    26     }
    27 
    28     void Request()
    29     {
    30         adaptee->SpecificRequest();
    31     }
    32 
    33 private:
    34     Adaptee *adaptee;
    35 };
    36 
    37 int main()
    38 {
    39     Target *target = (Target *)new Adapter;
    40     target->Request();
    41 }

    运行结果

    Specific request.

    代理模式 (proxy)

    名称:proxy(代理模式)

    意图:为其他对象提供一种代理以控制对这个对象的访问。

    适用环境

    在需要用比较通用和复杂的对象指针代替简单的指针的时候,使用Proxy模式。下面是一些可以使用Proxy模式常见情况:

    1. 远程代理(Remote Proxy )为一个对象在不同的地址空间提供局部代表。
    2. 虚代理(Virtual Proxy )根据需要创建开销很大的对象。
    3. 保护代理(Protection Proxy )控制对原始对象的访问。保护代理用于对象应该有不同的访问权限的时候。
    4. 智能指引(Smart Reference )取代了简单的指针,它在访问对象时执行一些附加操作。它的典型用途包括:
      1. 对指向实际对象的引用计数,这样当该对象没有引用时,可以自动释放它。
      2. 当第一次引用一个持久对象时,将它装入内存。
      3. 在访问一个实际对象前,检查是否已经锁定了它,以确保其他对象不能 改变它。
    5. android NDK 就是典型的 proxy 模式

    C++实现代码

    View Code
     1 class Subject
     2 {
     3 public:
     4 virtual void Request()=0;
     5 };
     6 
     7 class RealSubject : public Subject
     8 {
     9 public:
    10 void Request()
    11 {
    12    cout<<"Test."<<endl;
    13 }
    14 };
    15 
    16 class Proxy : public Subject
    17 {
    18 public:
    19 Proxy()
    20 {
    21    realSubject = NULL;
    22 }
    23 
    24 void Request()
    25 {
    26    if(!realSubject)
    27     realSubject = new RealSubject;
    28 
    29   realSubject->Request();
    30 }
    31 
    32 private:
    33 RealSubject *realSubject;
    34 };
    35 
    36 int main()
    37 {
    38 Proxy *proxy = new Proxy;
    39 proxy->Request();
    40 }

    行为型模式

    GOF 未提到的设计模式

    委托模式 (delegation)2

    名称:delegation(委托模式)

    意图:一个对象在外界来看好像实现了一些行为,但实际上是委托给相关的其他类来实现行为的。

    适用环境

    在不可以使用继承,而采用聚合时,必须使用这种技术。

    缺点:

    这个模式是典型的牺牲性能提高抽象程序的清晰程度. (或者说提高代码可读性)

    一个简单的Java例子

    这个例子中,C 拥有调用 A 中 f() 和 g() 的插口,看起来 C 好像有 A 的功能。

    View Code
     1 class A {
     2     void f() { system.out.println("A: doing f()"; }
     3    void g() { system.out.println("A: doing g()"; }
     4 }
     5 
     6 class C {
     7    // delegation
     8    A a = new A();
     9    void f() { a.f(); }
    10    void g() { a.g(); }
    11    // normal attributes
    12    X x = new X();
    13    void y() { /* do stuff */ }
    14 }
    15 
    16 void main() {
    17    C c = new C();
    18    c.f();
    19    c.g();
    20 }

    一个复杂些的 Java 例子

    使用接口+委托可以提高程序灵活性,和类型的安全性.这个例子中,C代理了A,B二 者之一.C可以在A,B之间切换.由于A,B都必须通过实现接口以实现功能,这就提高 了了类型安全性.作为折中,当然也需要写更多的代码。

    View Code
     1 interface I {
     2     void f();
     3    void g();
     4 }
     5 
     6 class A implements I {
     7    void f() { system.out.println("A: doing f()"; }
     8    void g() { system.out.println("A: doing g()"; }
     9 }
    10 
    11 class B implements I {
    12    void f() { system.out.println("B: doing f()"; }
    13    void g() { system.out.println("B: doing g()"; }
    14 }
    15 
    16 class C implements I {
    17    // delegation
    18    I i = new A();
    19    void f() { i.f(); }
    20    void g() { i.g(); }
    21    // normal attributes
    22    void toA() { i = new A(); }
    23    void toB() { i = new B(); }
    24 }
    25 
    26 void main() {
    27    C c = new C();
    28    c.f();
    29    c.g();
    30 }

    转至:http://www.linuxgraphics.cn/gui/design_pattern_ref.html

    另一篇很全的设计模式:http://hi.baidu.com/luv_resplendent/blog/item/7b315af2302ab01bb07ec5d2.html

    
    

     

     

  • 相关阅读:
    MyBatis_2
    JDBC(java database connectivity)
    异常的各种情况
    Spring(一)
    SpringMVC(四)
    SpringMVC(三)
    SpringMVC(二)
    springMVC文件上传、拦截器、数据校验
    springMVC数据相关
    初步接触springMVC
  • 原文地址:https://www.cnblogs.com/zhouchanwen/p/2601528.html
Copyright © 2011-2022 走看看