组合模式
什么是组合模式
组合模式是一种结构型设计模式, 你可以使用它将对象组合成树状结构, 并且能像使用独立对象一样使用它们。
为什么使用组合模式
组合模式为你提供了两种共享公共接口的基本元素类型: 简单叶节点和复杂容器。 容器中可以包含叶节点和其他容器。 这使得你可以构建树状嵌套递归对象结构。果你希望客户端代码以相同方式处理简单和复杂元素, 可以使用该模式。 组合模式中定义的所有元素共用同一个接口。 在这一接口的帮助下, 客户端不必在意其所使用的对象的具体类。
组合模式实现步骤
1.提供一个组件类:描述复杂元素的通用接口和方法
2.创建一个叶子节点类:描述简单元素
3.提供一个容器类:表示复杂元素
4.容器类中定义添加和删除子元素的方法
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Root {
public:
virtual void Display() = 0;
virtual void Add(Root* file) = 0;
virtual void Remove(Root* file) = 0;
virtual list<Root*> GetChild() = 0;
};
class File : public Root {
public:
File(string name) : m_name(name) {}
virtual void Display() { cout << m_name << endl; }
virtual void Add(Root* file) { return; }
virtual void Remove(Root* file) { return; }
list<Root*> GetChild() { return m_list; }
protected:
list<Root*> m_list;
string m_name;
};
class Folder : public Root {
public:
Folder(string name) : m_name(name) {}
virtual void Display() { cout << m_name << endl; }
virtual void Add(Root* file) { m_list.push_back(file); }
virtual void Remove(Root* file) { m_list.remove(file); }
list<Root*> GetChild() { return m_list; }
private:
list<Root*> m_list;
string m_name;
};
void ShowTree(Root* file, int level) {
list<Root*> root;
int i = 0;
for (int i = 0; i < level; i++) {
cout << "--";
}
file->Display();
root = file->GetChild();
if (!root.empty()) {
for (auto v : root) {
if (v->GetChild().empty()) {
for (int i = 0; i <= level; i++) {
cout << "--";
}
v->Display();
} else {
ShowTree(v, level + 1);
}
}
}
}
int main() {
Folder* root = new Folder("C:");
Folder* dir1 = new Folder("1_dir");
File* t1 = new File("t1.txt");
Folder* dir2 = new Folder("2_dir");
File* t2 = new File("t2.txt");
// root->Display();
root->Add(dir1);
root->Add(t1);
dir1->Add(dir2);
dir1->Add(t2);
ShowTree(root, 0);
return 0;
}
组合模式优缺点
优点
-
你可以利用多态和递归机制更方便地使用复杂树结构。
-
开闭原则。 无需更改现有代码, 你就可以在应用中添加新元素, 使其成为对象树的一部分。
缺点
-
对于功能差异较大的类, 提供公共接口或许会有困难。
-
在一些特定情况下,可以存在过度一般化组件接口, 使其变得令人难以理解。
C++模板模式:
//造对象
#include <iostream>
#include <string>
using namespace std;
class MakeObject {
public:
virtual void MakeHead() = 0;
virtual void MakeBody() = 0;
virtual void Garb() = 0;
void Make() {
MakeHead();
MakeBody();
Garb();
}
};
class MakeGirlFriend : public MakeObject {
public:
void MakeHead() { cout << "刘亦菲的头" << endl; }
void MakeBody() { cout << "杨幂的身材" << endl; }
void Garb() { cout << "穿古装" << endl; }
};
class MakeBoyFriend : public MakeObject {
public:
void MakeHead() { cout << "胡歌的头" << endl; }
void MakeBody() { cout << "彭于晏的身材" << endl; }
void Garb() { cout << "穿西装" << endl; }
};
int main() {
MakeObject* object = new MakeGirlFriend();
object->Make();
delete object;
object = new MakeBoyFriend();
object->Make();
delete object;
object = nullptr;
return 0;
}