Design Patterns/Structural Patterns

Composite Pattern (C++)

개발새발 2019. 4. 21. 22:20
반응형

Composite Pattern(복합체 패턴)

목적

부분과 전체의 계층을 표현하기 위해 객체들을 하나의 인터페이스(Component)로 묶어 트리 구조로 구조화 한다.

출처 : https://ko.wikipedia.org/wiki/%EC%BB%B4%ED%8F%AC%EC%A7%80%ED%8A%B8_%ED%8C%A8%ED%84%B4

사용 시나리오

1. 루트(/) 디렉토리는 여러 파일과 폴더를 포함하고 있다.

2. 폴더도 여러 파일과 폴더를 포함하고 있다.

 

[Component]

집합 관계에 정의될 모든 객체에 대한 인터페이스를 정의. Leaf와 Composite 클래스를 트리화 하기 위한 추상 클래스

class Component {
public:
    Component(string componentName) {
        this->componentName = componentName;
    }
    virtual ~Component(){ }
    
    virtual void ShowName() const = 0; //operation
    
protected:
    string componentName;
};

 

[Composite]

복수개의 Leaf와 Composite를 가지며 관리하는 클래스

class Folder : public Component {
public:
    Folder(string folderName)
    : Component(folderName)
    { }
    
    virtual void ShowName() const {
        cout << "child list" << endl;
        
        for (vector<Component*>::const_iterator it = children.begin();
             it != children.end(); ++it)
        {
            (*it)->ShowName();
        }
    }
    
    void addFile(Component* component) {
        children.push_back(component);
    }
    
private:
    vector<Component*> children;
};

[Leaf]

가장 말단의 역할을 하는 클래스

class File : public Component {
public:
    File(string fileName)
    : Component(fileName)
    { }
    
    virtual void ShowName() const {
        cout<< this->componentName <<endl;
    }
};

 

[사용 예]

root폴더 아래 config.txt와 user폴더가 있고 usr폴더 아래에 guest1,guest2파일이 있는 상황을 가정

/root - config.txt
         - /usr - guest1
                  - guest2

int main(int argc, const char * argv[]) {
    Folder* root = new Folder("root");
    root->addFile(new File("config.txt"));
    
    Folder* usr =new Folder("usr");
    root->addFile(usr);
    usr->addFile(new File("guest1"));
    usr->addFile(new File("guest2"));
    
    
    root->ShowName();
    return 0;
}

 

실행결과

root child list

config.txt

usr child list

guest1

guest2

반응형