반응형
Composite Pattern(복합체 패턴)
목적
부분과 전체의 계층을 표현하기 위해 객체들을 하나의 인터페이스(Component)로 묶어 트리 구조로 구조화 한다.
사용 시나리오
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
반응형
'Design Patterns > Structural Patterns' 카테고리의 다른 글
Facade Pattern (C++) (0) | 2019.10.27 |
---|---|
Bridge Pattern (C++) (0) | 2019.10.13 |
Decorator Pattern (C++) (0) | 2019.07.21 |
Adapter Pattern (C++) (0) | 2019.03.03 |
Structural Pattern (구조패턴) (0) | 2019.03.03 |