[C + + design mode] Composite combined mode

Source: Internet
Author: User

There are also many other translation names in the combination (Composite) mode, such as compositing mode, tree mode, and so on. The definition in design mode is that the objects are organized in a tree-shaped structure to achieve a "partial-overall" hierarchy, which makes the client consistent with the use of individual objects and composite objects.
The environment in which you can use the composition pattern from the definition is: you want to represent the "partial-whole" hierarchy of objects in your design; you want users to ignore the combination of objects and individual objects, uniformly use all objects in the composite structure.
Look at the composition of the combo pattern.
1) Abstract Component role component: It declares an interface for an object in a composition, or it can implement default behavior for a common interface.
2) leaf component role leaf: Represents a leaf node object in a composition--an interface that implements an abstract component role declaration without a child node.

3) Branch Component role composite: Represents the Branch node object in the composition--there are child nodes, the interface that implements the abstract component role declaration, and the storage sub-parts.


Component:

Declares an interface for an object in a composition;
The default behavior of all classes of common interfaces is implemented in the appropriate case;
Declares an interface for accessing and managing component subcomponents.


Leaf:

The leaf node object is represented in the composition, and the leaf node has no child nodes;
Defines the behavior of a leaf node in a composition.


Composite:

Define the behavior of those parts that have subassemblies;
Stores the child parts.
Client:

An object that combines parts by manipulating the component interface.

The management of the child object must be provided in the combined mode, otherwise the addition and deletion of the child object cannot be completed, and the flexibility and extensibility will be lost. But is the management method declared in component or in composite?
One way is to declare all the methods used to manage the subclass object in component to maximize the component interface (as shown). The goal is to make the client seem to have no distinction between leaves and branches at the interface level-transparency. But there is no subclass of leaves, so some of the methods component declare are not suitable for leaves. This also poses some security issues.

Another way is to declare all the methods used to manage subclass objects in composite (as shown). This avoids the security problem of the previous approach, but because the leaves and branches have different interfaces, they lose their transparency.

"Design mode," a book that: in this model, relative to security, we have more emphasis on transparency. Methods that are not required within the leaf node in the first way can be resolved using either empty processing or exception reporting.

#include <iostream> #include <string> #include <vector>using namespace std;//     Abstract part classes describe the behavior common to all future parts class Component{public:component (string name): M_strcompname (name) {} virtual ~component () {}     virtual void operation () = 0;     virtual void Add (Component *) = 0;     virtual void Remove (Component *) = 0;     Virtual Component *getchild (int) = 0;     Virtual String GetName () {return m_strcompname; } virtual void Print () = 0;protected:string m_strcompname;}; Class Leaf:public Component{public:leaf (string name): Component (name) {} void operation () {C     out<< "I ' m" <<m_strCompname<<endl;          } void Add (Component *pcomponent) {} void Remove (Component *pcomponent) {} Component *getchild (int index) {     return NULL; } void Print () {}};class composite:public component{public:composite (string name): Component (name) {} ~ Composite () {Vector<compOnent *>::iterator it = M_veccomp.begin (); while (It! = M_veccomp.end ()) {if (*it! = NULL) {cout<< "--                    --delete "<< (*it)->getname () <<"----"<<endl;                    Delete *it;               *it = NULL;               } m_veccomp.erase (it);          it = M_veccomp.begin ();     }} void operation () {cout<< "I ' m" <<m_strCompname<<endl;     } void Add (Component *pcomponent) {m_veccomp.push_back (pcomponent); } void Remove (Component *pcomponent) {for (vector<component *>::iterator it = M_veccomp.begin (); I T! = M_veccomp.end (); ++it) {if ((*it)->getname () = = Pcomponent->getname ()) {if                    (*it! = NULL)                         {Delete *it;                    *it = NULL;              }      M_veccomp.erase (IT);               Break               }}} Component *getchild (int index) {if (Index > M_veccomp.size ()) {          return NULL;     } return m_veccomp[index-1]; } void Print () {for (vector<component *>::iterator it = M_veccomp.begin (); It! = M_veccomp.end ();          ++it) {cout<< (*it)->getname () <<endl; }}private:vector<component *> m_veccomp;};     int main (int argc, char *argv[]) {Component *pnode = new Composite ("Beijing Head Office");     Component *pnodehr = new Leaf ("Beijing Human Resources Department");     Component *psubnodesh = new Composite ("Shanghai Branch");     Component *PSUBNODECD = new Composite ("Chengdu Branch");     Component *psubnodebt = new Composite ("Baotou Branch");     Pnode->add (Pnodehr);     Pnode->add (Psubnodesh);     Pnode->add (PSUBNODECD);    Pnode->add (PSUBNODEBT); Pnode->print ();     Component *PSUBNODESHHR = new Leaf ("Shanghai Human Resources Department");     Component *PSUBNODESHCG = new Leaf ("Shanghai Purchasing Department");     Component *psubnodeshxs = new Leaf ("Shanghai Sales Department");     Component *PSUBNODESHZB = new Leaf ("Shanghai Quality Supervision Department");     Psubnodesh->add (PSUBNODESHHR);     Psubnodesh->add (PSUBNODESHCG);     Psubnodesh->add (PSUBNODESHXS);     Psubnodesh->add (PSUBNODESHZB);     Pnode->print ();     Company depressed, need to close the Shanghai Quality Supervision Department Psubnodesh->remove (PSUBNODESHZB);          if (pnode! = NULL) {Delete pnode;     Pnode = NULL; } return 0;}

One of the keys to composite is an abstract class that can represent both the leaf and the composite, so the component interface should be maximized when actually implemented. The component class should define as many common operations as possible for the leaf and composite classes. The component class typically provides default implementations for these operations, and the leaf and composite subclasses can redefine them;


Component should implement a component list, in the above code, I am the list maintained in composite, because there is no possibility of child composite in the leaf, so a composite list is maintained in component , thus reducing the waste of memory;


Memory release; Because of the tree structure, when the parent node is destroyed, all child nodes must also be destroyed, so, I am in the destructor of the maintenance of the component list of the unified destruction, so that the client can eliminate the problem of frequent destruction of child nodes;


Since the component interface provides a maximized interface definition, some operations do not apply to the leaf node, for example: the leaf node does not have add and remove operations, because the composite mode masks the difference between parts and the whole, In order to prevent the customer from illegal add and remove operations on the leaf, in the actual development process, when the add and remove operations, we need to make a corresponding judgment to determine whether the current node is composite.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[C + + design mode] Composite combined mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.