TIL0207

jelly·2025년 2월 7일

프로토타입 패턴은 객체를 복제하여 새로운 객체를 생성하는 디자인 패턴입니다. C++에서 프로토타입 패턴을 구현하는 간단한 예시 코드를 아래에 제공하겠습니다.

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

// Prototype 인터페이스
class Prototype {
public:
    virtual std::unique_ptr<Prototype> clone() const = 0;
    virtual void info() const = 0;
    virtual ~Prototype() = default;
};

// ConcretePrototype 클래스
class ConcretePrototypeA : public Prototype {
public:
    ConcretePrototypeA(const std::string& name) : name(name) {}

    std::unique_ptr<Prototype> clone() const override {
        return std::make_unique<ConcretePrototypeA(*this);
    }

    void info() const override {
        std::cout << "ConcretePrototypeA: " << name << std::endl;
    }

private:
    std::string name;
};

// 또 다른 ConcretePrototype 클래스
class ConcretePrototypeB : public Prototype {
public:
    ConcretePrototypeB(const std::string& name) : name(name) {}

    std::unique_ptr<Prototype> clone() const override {
        return std::make_unique<ConcretePrototypeB(*this);
    }

    void info() const override {
        std::cout << "ConcretePrototypeB: " << name << std::endl;
    }

private:
    std::string name;
};

// 클라이언트 코드
int main() {
    // 원본 객체 생성
    ConcretePrototypeA prototypeA("Prototype A");
    ConcretePrototypeB prototypeB("Prototype B");

    // 객체 복제
    auto cloneA = prototypeA.clone();
    auto cloneB = prototypeB.clone();

    // 정보 출력
    cloneA->info();
    cloneB->info();

    return 0;
}
이 코드는 Prototype 인터페이스와 두 개의 구체적인 프로토타입 클래스(ConcretePrototypeA, ConcretePrototypeB)를 정의합니다. 각 프로토타입 클래스는 clone 메서드를 통해 자신을 복제할 수 있습니다. 클라이언트 코드에서는 원본 객체를 생성하
profile
jelly

0개의 댓글