zoukankan      html  css  js  c++  java
  • 5 创建型模式-----原型模式

    模式动机:在软件系统中,有些对象的创建过程非常复杂,但是又需要频繁创建,这时候需要提供一个原型对象,使用时只需要复制这个原型对象就可以了。

    模式定义(Prototype Pattern)使用原型实例指定创建对象的类型,然后通过复制原型对象来创建新对象。

     

    模式结构图:

    模式代码:

    bt_原型模式.h

     1 #ifndef PP_H
     2 #define PP_H
     3 
     4 #include <iostream>
     5 
     6 using namespace std;
     7 
     8 /*
     9     原型类
    10 */
    11 class Prototype
    12 {
    13 public:
    14     virtual ~Prototype(){ }
    15     virtual Prototype* clone() = 0;
    16 };
    17 
    18 /*
    19     具体原型类
    20 */
    21 class ConcretePrototypeA : public Prototype
    22 {
    23 public:
    24     ConcretePrototypeA(){ }
    25     virtual Prototype* clone()
    26     {
    27         return new ConcretePrototypeA(*this);
    28     }
    29 
    30 private:
    31     ConcretePrototypeA(const ConcretePrototypeA& cp)
    32     {
    33         cout << "复制了一份当前原型A的实例" << endl;
    34     }
    35 };
    36 class ConcretePrototypeB : public Prototype
    37 {
    38 public:
    39     ConcretePrototypeB(){ }
    40     virtual Prototype* clone()
    41     {
    42         return new ConcretePrototypeB(*this);
    43     }
    44 
    45 private:
    46     ConcretePrototypeB(const ConcretePrototypeB& cp)
    47     {
    48         cout << "复制了一份当前原型B的实例" << endl;
    49     }
    50 };
    51 
    52 #endif // PP_H

    bt_原型模式.cpp

     1 #include "bt_原型模式.h"
     2 
     3 int main()
     4 {
     5     Prototype* pA = new ConcretePrototypeA;
     6     Prototype* pB = new ConcretePrototypeB;
     7     Prototype* copyOfA = pA->clone();
     8     Prototype* copyOfB = pB->clone();
     9 
    10     cout << "pA == copyOfA --> " << (pA == copyOfA ? true : false) << endl;
    11 
    12     delete copyOfA;
    13     delete copyOfB;
    14     delete pA;
    15     delete pB;
    16 
    17     return 0;
    18 }
    
    

     

    模式优缺点:使用原型模式可以简化对象的创建过程,例如常用的Ctrl + C(复制)和Ctrl + V(粘贴)操作就是原型模式的应用。其复制得到的对象与原型对象是两个类型相同但内存地址不同的对象。

     

     

  • 相关阅读:
    感觉每天打开自己的博客园, 想编程的心情就多了起来~~~
    算法图解相关代码整理
    github cli
    What's WebFlux ? And how to use it ? 一股有咖喱味的WebFlux简介
    style
    gradle 1
    gradle打包可运行jar
    外面下着雨
    天晴朗 看花儿多多开放
    Full Stack Reactive with React and Spring WebFlux
  • 原文地址:https://www.cnblogs.com/benxintuzi/p/4538603.html
Copyright © 2011-2022 走看看