创建型模式——原型模式

原型设计模式适用于以下情况:
• 当一个系统应该独立于它的产品创建、构成和表示时;
• 当要实例化的类是在运行时指定时,例如,通过动态装载;
• 为了避免创建一个与产品类层次平行的工厂类层次时;
• 当一个类的实例只能有几个不同状态组合中的一种时;

下面是一个原型模式的示例程序:

#include <iostream>
#include <memory>
#include <string>

// Step 1: The Prototype Base Class
class DocTemplate {
public:
    virtual ~DocTemplate() = default;
    
    // The "Make a Copy" operation
    virtual std::unique_ptr<DocTemplate> clone() const = 0;
    
    virtual void show() const = 0;
    virtual void setContent(const std::string& text) = 0;
};

// Step 2: Concrete Prototype (Resume Template)
class Resume : public DocTemplate {
private:
    std::string header_ = "=== RESUME TEMPLATE ===\nFormat: 1-Page, Arial Font\n";
    std::string content_ = "[Empty]";

public:
    // Clone copies the entire existing object state
    std::unique_ptr<DocTemplate> clone() const override {
        return std::make_unique<Resume>(*this); 
    }

    void setContent(const std::string& text) override { content_ = text; }
    
    void show() const override {
        std::cout << header_ << "Content: " << content_ << "\n\n";
    }
};

// Step 3: Concrete Prototype (Invoice Template)
class Invoice : public DocTemplate {
private:
    std::string header_ = "=== INVOICE TEMPLATE ===\nFormat: Table layout, Tax included\n";
    std::string content_ = "[Empty]";

public:
    std::unique_ptr<DocTemplate> clone() const override {
        return std::make_unique<Invoice>(*this);
    }

    void setContent(const std::string& text) override { content_ = text; }
    
    void show() const override {
        std::cout << header_ << "Content: " << content_ << "\n\n";
    }
};

// Client Code
int main() {
    // 1. Set up our golden master templates
    std::unique_ptr<DocTemplate> masterResume = std::make_unique<Resume>();
    std::unique_ptr<DocTemplate> masterInvoice = std::make_unique<Invoice>();

    // 2. Someone wants to write a resume. We CLONE the template.
    std::unique_ptr<DocTemplate> johnsResume = masterResume->clone();
    johnsResume->setContent("John Doe - Software Engineer Experience...");

    // 3. Someone wants to write an invoice. We CLONE the template.
    std::unique_ptr<DocTemplate> clientInvoice = masterInvoice->clone();
    clientInvoice->setContent("Order #1024 - Total: $150.00");

    // 4. Display the results
    std::cout << "--- Printing Cloned Documents ---\n";
    johnsResume->show();
    clientInvoice->show();

    return 0;
}

程序运行结果如下:

$ g++ -o main main.cpp
$ ./main
--- Printing Cloned Documents ---
=== RESUME TEMPLATE ===
Format: 1-Page, Arial Font
Content: John Doe - Software Engineer Experience...

=== INVOICE TEMPLATE ===
Format: Table layout, Tax included
Content: Order #1024 - Total: $150.00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值