본문 바로가기
Design Patterns

[Design Patterns] Composite Pattern

by matters_ 2021. 7. 26.

Composite Pattern

클라이언트에서 단일 객체와 복합 객체 모두 동일하게 다루기 위해 사용하는 디자인 패턴

A design pattern used by clients to treat both single and complex objects the same.

Purpose

각각의 객체는 독립적으로 동일한 인터페이스를 통해 중첩된 객체로 구현되어 계층구조 객체를 쉽게 만들수 있도록 합니다. 

Facilitates the creation of object hierarchies where each object can be treated independently or as a set of nested objects through the same interface.

Use When 

    • 객체가 계층적으로 표현될 필요성이 있을 때
      Hierarchical representations of objects are needed.
    • 객체와 부분 객체들이 동일하게 다뤄질 필요성이 있을 때
      Objects and compositions of objects should be treated uniformly.

Example Code

#include <iostream>
#include <vector>

class Component 
{
    public:
        Component() {}
        virtual ~Component() {}
        virtual void print(int) = 0;
};

class Composite : public Component
{
public:
    ~Composite() {}
    Composite() {}
    Composite(std::string id) : m_id(id) {}
    void add(Component *input){
        m_comp.push_back(input);
    }
    void print(int tap = 0) {
        for (int i = 0; i < tap; i++) printf("\t");
        printf("Composite : %s\n",m_id.c_str());

        for (auto dir : m_comp) {
            dir->print(tap + 1);
        }
    }

private:
    std::vector<Component*> m_comp;
    std::string m_id;
};

class Leaf : public Component {
public:
    ~Leaf() {}
    Leaf() {}
    Leaf(std::string id) : m_id(id) {}
    void print(int tap = 0) {
        for(int i= 0; i < tap ; i++) printf("\t");
        printf("Leaf : %s\n",m_id.c_str());
    }
private:
    std::string m_id;
};

int main() {
    Composite *market = new Composite("Market");
    Composite *fruits = new Composite("Fruits");
    Composite *beef = new Composite("Beef");
    Composite *beverages = new Composite("Beverages");
    Leaf *specialties = new Leaf("Specialties");
    market->add(specialties);
   
    fruits->add(new Leaf("Grape"));
    fruits->add(new Leaf("Apple"));
    fruits->add(new Leaf("Melon"));
    market->add(fruits);

    beef->add(new Leaf("Pig"));
    beef->add(new Leaf("Cow"));
    beef->add(new Leaf("Duck"));
    market->add(beef);

    beverages->add(new Leaf("Coffee"));
    beverages->add(new Leaf("Tea"));
    beverages->add(new Leaf("Soft drink"));
    market->add(beverages);

    market->print();
    
    return 0;
}

Output

Reference

https://en.wikipedia.org/wiki/Composite_pattern

'Design Patterns' 카테고리의 다른 글

[Design Patterns] (Abstract) Factory Pattern  (0) 2021.08.06
[Design Patterns] Strategy Pattern  (0) 2021.07.30

댓글