将对象组合成树形结构,以表示“部分-整体”的层次结构。Component使得用户对单个对象和组合对象的使用具有一致性。
实现代码
class Graphic{
public:
Graphic(int a){
index = a;
}
virtual void Draw(){
std::cout<<"never show"<<std::endl;
}
virtual void Add(Graphic *g){
std::cout<<"can't add"<<std::endl;
}
virtual void Remove(Graphic *g){
std::cout<<"can't remove"<<std::endl;
}
int index;
};
class Text : public Graphic{
public:
Text(int a):Graphic(a){}
void Draw() override {
std::cout<<"Text"<<index<<std::endl;
}
};
class Line : public Graphic{
public:
Line(int a):Graphic(a){}
void Draw() override {
std::cout<<"Line"<<index<<std::endl;
}
};
class Picture : public Graphic{
public:
Picture(int a):Graphic(a){}
void Draw() override {
std::cout<<"Picture"<<index<<std::endl;
for(auto x :set){
x->Draw();
}
}
void Add(Graphic *g) override {
set.insert(g);
}
void Remove(Graphic *g) override {
set.erase(g);
}
private:
std::set<Graphic *> set;
};
int main(){
Graphic *root = new Picture(1);//root
Graphic *pic1 = new Picture(2);Graphic *pic2 = new Picture(3);//subdir
Graphic *text1 = new Text(4);Graphic *text2 = new Text(5);//text
Graphic *text3 = new Text(6);Graphic *text4 = new Text(7);//text
Graphic *text5 = new Text(8);
Graphic *line1 = new Line(1);Graphic *line2 = new Line(2);
Graphic *line3 = new Line(3);
root->Add(pic1);root->Add(pic2);
pic1->Add(text1);pic1->Add(text2);pic1->Add(text3);pic1->Add(line1);
pic2->Add(text4);pic2->Add(text5);pic2->Add(line2);pic2->Add(line3);
root->Draw();
}
结果
Picture1
Picture2
Text4
Text5
Text6
Line1
Picture3
Text7
Text8
Line2
Line3
参与者
- Component(Graphic)
- Leaf(Text,Line)
- Composite(Picture)
- Client
适用性
- 你想表示对象的部分-整体层次结构
- 你希望忽略组合对象与单个对象的不同,用户将统一的使用组合结构中所有对象
参考
- https://www.cnblogs.com/snaildev/p/7647190.html
- 《设计模式:可复用面向对象软件的基础》