4、创建型模式——原型模式(Prototype)

意图

原型模式(Prototype)是一种创建型设计模式, 使你能够复制已有对象, 而又无需使代码依赖它们所属的类。

结构

原型式的结构包含以下几个角色:

  • 抽象原型类(AbstractPrototype):声明克隆clone自身的接口
  • 具体原型类(ConcretePrototype):实现clone接口
  • 客户端(Client):客户端中声明一个抽象原型类,根据客户需求clone具体原型类对象实例

在这里插入图片描述

代码

Prototype.h:

#ifndef PROTOTYPE_H_
#define PROTOTYPE_H_

// 抽象原型类
class Object
{
public:
    virtual Object* clone() = 0;
};

#endif //PROTOTYPE_H_

ConcretePrototype.h:

#ifndef CONCRETE_PROTOTYPE_H_
#define CONCRETE_PROTOTYPE_H_

#include<iostream>
#include<string>
#include"Prototype.h"

// 邮件的附件
class Attachment
{
public:
    void set_content(std::string content){ content_ = content; }
    std::string get_content(){ return content_; }

private:
    std::string content_;
};
// 具体原型:邮件类
class Email : public Object
{
public:
    Email(){}
    Email(std::string text, std::string attachment_content):text_(text),attachment_(new Attachment())
    {
        attachment_->set_content(attachment_content);
    }
    ~Email()
    {
        if(attachment_ != nullptr)
        {
            delete attachment_;
            attachment_ = nullptr;
        }
    }
    void display()
    {
        std::cout << "------------查看邮件------------" << std::endl;
        std::cout << "正文: " << text_ << std::endl;
        std::cout << "邮件: " << attachment_->get_content() << std::endl;
        std::cout << "------------查看完毕--------" << std::endl;
    }

    //深拷贝
    Email* clone() override
    {
        return new Email(this->text_, this->attachment_->get_content());
    }
	void changeText(std::string new_text)
    {
        text_ = new_text;
    }

    void changeAttachment(std::string content)
    {
        attachment_->set_content(content);
    }
	private:
    std::string text_;
    Attachment* attachment_ = nullptr;
};
#endif   //CONCRETE_PROTOTYPE_H_

main.cpp:

#include<iostream>
#include"ConcretePrototype.h"

int main()
{
    Email* email = new Email("最初的文案","最初的附件");
    Email* copy_email = email->clone();
    copy_email->changeText("新文案");
    copy_email->changeAttachment("新附件");
    std::cout<<"copy email:"<<std::endl;
    copy_email->display();

    delete email;
    delete copy_email;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值