戏说原型模式之如何快速创建一个“对象”

介绍一下

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。还要再具体的就去菜鸟教程看吧——原型模式|菜鸟教程
这里说说我自己的感悟,当一个类有很多属性的时候,你又不太熟悉其属性,这个时候创建一个对象还要填充属性值就有点麻烦了。
那怎么办呢?直接克隆一个现成的吧,我才不管它有哪些属性,既然它已经存在了而我又想要对象,那就把它拿过来给我克隆出一个一模一样的来,然后它也是我的了hhhhhhhhh。
再结合数据库来说说,我们都知道读数据库是一种比较消耗CPU的操作,可是程序运行时又时不时的需要读取数据库里面的数据鸭,这个时候我们就在程序运行的开始将数据库初始化到内存来吧,以后要创建对象什么的都直接来读取最初创建的内存数据就ojbk了。
这样说可能有点抽象了,那下面就结合UML图和代码来娓娓道来吧!

UML图

这里写图片描述
gril是一个抽象类,具体想要什么样的gril自己实现去吧,而我想要甜甜的女孩子,狗头.jpg

CODE

girl.h

#ifndef _GIRL_
#define _GIRL_

#include <string>
#include <iostream>

using namespace std;

class girl
{
public:
    int m_height;
    int m_weight;
    string m_face;
    string m_character;
    virtual girl* clone() = 0;
    virtual void display() = 0;
};

class sweet_girl:public girl
{
public:
    sweet_girl(int height, int weight, string face, string character)
    {
        m_height = height;
        m_weight = weight;
        m_face = face;
        m_character = character;
    }
    sweet_girl(const girl* her)
    {
        m_height = her->m_height;
        m_weight = her->m_weight;
        m_face = her->m_face;
        m_character = her->m_character;
    }
    girl* clone()
    {
        return new sweet_girl(*this);
    }
    void display()
    {
        cout << "there is a " <<  m_height << "cm," << m_weight;
        cout << "kg," << m_face << "," << m_character << " girl of me." << endl;
    }
};

#endif
prototype_mode.cpp

#include "girl.h"
#include "iostream"

using namespace std;

int main(int argc, char const *argv[])
{
    //y是一个已经存在的对象,但她不是我的
    girl *y = new sweet_girl(164, 46, "cute face", "sweet");
    //可是我又想要,那怎么办呢?直接把她拿过来吧
    girl *my_girl = y->clone();
    my_girl->display();
    //这种对象反正我才不要释放,而且我才不会让程序结束,让系统来回收资源,微笑.jpg
    while(1); 
    return 0;
}

运行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/LonelyGambler/article/details/82559964
今日推荐