-
StackOverflow 文档
-
Design patterns 教程
-
复合图案
-
一个哑文件管理器的伪代码
/*
* Component is an interface
* which all elements (files,
* folders, links ...) will implement
*/
class Component
{
public:
virtual int getSize() const = 0;
};
/*
* File class represents a file
* in file system.
*/
class File : public Component
{
public:
virtual int getSize() const {
// return file size
}
};
/*
* Folder is a component and
* also may contain files and
* another folders. Folder is a
* composition of components
*/
class Folder : public Component
{
public:
void addComponent(Component* aComponent) {
// mList append aComponent;
}
void removeComponent(Component* aComponent) {
// remove aComponent from mList
}
virtual int getSize() const {
int size = 0;
foreach(component : mList) {
size += component->getSize();
}
return size;
}
private:
list<Component*> mList;
};