Definition: Combine objects into a tree structure to represent a "partial whole" hierarchy. The combination mode ensures consistency between the use of a single object and a composite object.
Composition:
1. component is the object declaration interface in the combination. When appropriate, it implements the default behavior of interfaces common to all classes. Declare an interface to access and manage component sub-parts.
2. Leaf indicates the leaf node object in the combination, and the leaf node does not have any child nodes.
3. Composite defines the behavior of a branch node, which is used to store sub-parts. operations related to sub-parts are implemented in the component interface, such as adding and removing.
Take a file structure as an example.
Each file or directory can be regarded as a node, and a directory node can be added or deleted.
First, define an abstract base class node.
class Node{public:virtual void Add(Node* tmp)=0;virtual void Remove()=0;virtual void Display(string str)=0;};
No delete operation is added for file nodes.
class File : public Node{private:string Name;void Add(Node* c){}void Remove(){}public:File(string name) { Name = name; }void Display(string str){string strtmp = str + Name;cout<<strtmp<<endl;}};
For folders, you can use a linked list to store their subfolders and files.
class DirFolder :public Node{private:list<Node*> subfolder;string Name;public:int length = 0;DirFolder(string name) { Name = name; }void Add(Node* tmp){length = length + 1;subfolder.push_back(tmp);}void Remove(){if (length == 0) return;length = length - 1;subfolder.pop_back();}void Display(string str){cout<<str<<Name<<endl;str = str + "---";for (Node* component:subfolder){component->Display(str);}}};
Test:
Int main () {dirfolder root ("root"); // Add file * file1 = new file ("file1"); root. add (file1); // Add the subfolders file * file2 = new file ("file2"); root. add (file2); // Add the file dirfolder * subdir = new dirfolder ("subdir"); file * file3 = new file ("file3 "); subdir-> Add (file3); file * file4 = new file ("file4"); subdir-> Add (file4); // Delete the subfolders root. add (subdir); root. display (""); root. remove (); root. display (""); Return 0 ;}
Applicable:
Indicates the part of the object-the overall hierarchy
When the whole and part need to be treated in the same way.