Design pattern combination mode (Composite) essence

Source: Internet
Author: User
Tags define null

23 seed Gof Design patterns are generally divided into three categories: the creation mode, the structure model, the behavior pattern.

Creating instances of schema abstraction, they help how to create a system independent, which is a combination of these objects and statements.

Create a class schema change instance that uses an inherited class. The creation of an object type model will also delegate the instantiation of an object.

The creation pattern has two recurring themes. First, they encapsulate the information about which detailed classes the system uses. Second, they hide how instances of these classes are created and put together. What the whole system knows about these objects is the interfaces defined by the abstract classes. So. Create a pattern in what is created. Who created it, how it was created, and when to create these aspects gave very great flexibility.

They agree to configure a system with "product" objects that differ very much in structure and function. The configuration can be static (that is, specified at compile time), or it can be dynamic (at execution time).

Structured patterns involve how classes and objects are combined to get a larger structure. The structure class pattern adopts the inheritance mechanism to combine interfaces or implementations. A structured object pattern is not a combination of interfaces and implementations, but rather a description of some of the ways in which some objects are combined to achieve new functionality. Because of the ability to change the composition of objects at execution time, object composition is more flexible, and such a mechanism is not possible with static class combinations.

Behavioral patterns involve the allocation of duties between algorithms and objects. The behavior pattern not only describes the patterns of objects or classes, but also describes the communication patterns between them.

These patterns depict complex control flows that are difficult to track at execution time. They shift the user's attention from the control flow to the contact between objects. The behavior class pattern uses the inheritance mechanism to dispatch behavior between classes.

The Behavior object pattern uses object compositing instead of inheritance. Some behavioral object pattern descriptions describe how a set of peers can work together to complete a task in which either object cannot be completed alone.

The creation pattern consists of: 1, FactoryMethod (factory method mode), 2, abstract Factory (Abstraction Factory mode), 3, Singleton (singleton mode), 4, builder (builder mode, generator mode). 5, Prototype (prototype mode).

The structure mode includes : 6, Bridge (bridging mode), 7, Adapter (adapter mode). 8, Decorator (decorative mode), 9, Composite (combination mode), 10, Flyweight (enjoy meta mode). 11, Facade (appearance mode), 12, Proxy (agent mode).

The behavior pattern consists of: 13, Templatemethod (template method mode). 14, strategy (strategy mode). 15, State (status mode), 16, OBSERVER (Observer mode), 17, Memento (Memo mode). 18, Mediator (intermediary mode). 19, command (order mode), 20, Visitor (Interview mode), 21, Chain of Responsibility (responsibility chain mode), 22, Iterator (iterator mode), 23, Interpreter (interpreter mode).

Factory Method: Defines an interface for creating objects, so that subclasses decide which class to instantiate. The Factory method defers the instantiation of a class to its subclasses.

Abstract Factory: Provides an interface to create a series of related or interdependent objects. Without having to specify their detailed class.

Singleton: Ensure that a class has only one instance and provides a global access point to it.

Builder: Separates the construction of a complex object from its representation so that the same build process can create different representations.

Prototype: Specifies the kind of object created with the prototype instance. and create a new object by copying the prototype.

Bridge: Separates the abstract part from its implementation, so that both can change independently.

Adapter: Transforms the interface of a class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not be able to work together because of incompatible interfaces.

Decorator: Dynamically add some additional responsibilities to an object. In terms of extended functionality. The decorator mode is more flexible than the way the subclass is generated.

Composite: Combines objects into a tree structure to represent a "partial-overall" hierarchy. Composite enables customers to have consistent use of individual objects and composite objects.

Flyweight: Use sharing technology to effectively support a large number of fine-grained objects.

facade: Provides a consistent interface for a set of interfaces in a subsystem, and the facade schema defines a high-level interface. This interface makes this subsystem easier to use.

Proxy: Provides an agent for other objects to control access to this object.

Template Method: Defines the skeleton of an algorithm in an operation. Some of the steps are deferred to subclasses.

The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

Strategy: Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be changed independently of the customer using it.

State: Agrees that an object changes its behavior when its internal states change. The object appears to have changed the class it belongs to.

Observer: Defines a one-to-many dependency between objects so that when the state of an object changes, all objects that depend on it are notified and refreshed on their own initiative.

Memento: Without damaging the encapsulation. captures the internal state of an object. and save this state outside of the object.

The object can then be restored to the saved state.

Mediator: Encapsulates a series of object interactions with a mediation object.

Intermediaries allow objects to be loosely coupled without having to explicitly cross-reference each other, and can independently change the interaction between them.

Command: Encapsulates a request as an object, allowing you to use different requests to account for the customer. Queues or logs request logs for requests, and supports operations that can be canceled.

Visitor: Represents an operation that acts on elements in an object's structure. It enables you to define new actions that act on these elements without changing the class of each element.

Chain of Responsibility: coupling between the sender and receiver of the cancellation request. and allow multiple objects to have the opportunity to handle this request. Connect these objects as a chain. and pass the request along this chain. Until there is an object that handles it.

Iterator: Provides a way to access individual elements of an aggregation object in a sequential manner without exposing the object's internal representation.

interpreter: Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.

Composite: (1), intent: Group objects into a tree structure to represent the "partial--overall" hierarchy.

Composite makes the user consistent with the use of individual objects and composite objects.

(2), Applicability: A, you want to represent the part of the object-the overall hierarchy; B, you want users to ignore the combination object and the individual object, the user will uniformly use all the objects in the composite structure.

(3), advantages and disadvantages: A, defines a class hierarchy containing basic objects and composite objects: basic objects can be combined into more complex objects, and this combination of objects can be combined, so that continuous recursion. In the customer code. Combining objects can be used wherever they are used in the base object. B. Simplify customer code: Customers can consistently use composite structures and individual objects. Often users do not know (and do not care) whether the processing is a leaf node or a composite component. This simplifies the customer code. Because there is no need to write some functions that are flooded with SELECT statements in those classes that define the composition. C, make it easier to add new types of components: the newly defined composite or leaf subclass itself proactively works with existing structures and customer code. The client program does not need to be changed by the new component class.

D, make your design more generalized: Sometimes you want a combination to have only certain components. When using composite. You cannot impose these constraints on a type system, but must be checked at execution time.

(4), note: A, the display of the parent part reference: Keeping references from subassemblies to parent parts can simplify the traversal and management of the composite structure. The parent part reference simplifies the move up of the structure and removes the component, and the parent part reference also supports chain of Responsibility at the same time. B, shared components: Shared components are very useful. For example, it can reduce the need for storage. However, when a component has only one parent part, it is very difficult to share components. C, maximizing the component interface: one of the purposes of the composite mode is to make the user unaware of the detailed leaf and composite classes they are using.

To achieve this, the composite class should define as many common operations as possible for the leaf and composite classes. The composite class typically provides default implementations for these operations, and the leaf and composite subclasses can redefine them. D. Declare the operations of the child parts management.

E, component should implement a component list: You might want to define a child node collection as an instance variable in the component class. And this component class also declares some operations to access and manage child nodes.

However, in the base class to hold the child class pointer, the leaf node will lead to wasted space, because the leaf node does not have child nodes at all.

Only when the number of neutron classes in the structure is relatively small is it worthwhile to use such a method. F, subassembly Ordering: If you need to consider the order of the child nodes, you must design the access and management interfaces of the sub-nodes carefully. To manage the child node sequence. The iterator model can give some guidance in this regard. G, using fast buffer storage to improve performance: assuming you need to iterate or find the combination frequently, the composite class is able to buffer the storage of its child nodes to traverse or find relevant information. H, who should delete component: In a language that does not have a garbage collection mechanism, when a composite is destroyed, it is usually best for composite to delete its child nodes. But there is one exception. That is, the leaf object does not change and therefore can be shared. I, storage components The best data structure: Composite can use a variety of data structures to store their child nodes, including connection lists, trees, arrays, and hash tables.

The choice of data structure depends on efficiency.

In fact, there is no need to use a common data structure. Sometimes for each child node. Composite has a variable corresponding to it. This requires every subclass of composite to implement its own management interface.

(5), correlation mode: A, usually part----parent part connection for responsibilityof chain mode.

B, decorator mode is often used in conjunction with the composite mode.

When used together with decorations and combinations. They usually have a common parent class. The adornment must therefore support the component interface with Add, remove, and getchild operations. C, Flyweight lets you share components, but no longer refer to their parent parts. D, iterator can be used to traverse composite. E, visitor the operations and behavior localization that should have been distributed in the composite and leaf classes.

One of the problems in the implementation of the composite pattern is to provide a management strategy for the child nodes (Leaf). The implementation methods that can be provided are: vector, array, linked list, hash table and so on.

The composite pattern has a similar structure to the decorator pattern, but the composite pattern is designed to construct classes, and the decorator pattern is to add responsibilities to objects without generating subclasses. The decorator mode is heavily decorated, while the composite mode is represented.

Demo Sample Code 1:

#include <iostream> #include <string> #include <vector>using namespace Std;class component{public: String M_strname; Component (String strName) {m_strname = StrName;} virtual void Add (component* com) = 0;virtual void Display (int ndepth) = 0;}; Class Leaf:public Component{public:leaf (String strName): Component (strName) {}virtual void Add (component* com) {cout&lt ;< "Leaf can ' t add" &LT;&LT;ENDL;} virtual void Display (int ndepth) {string strtemp;for (int i = 0; i < ndepth; i + +) strtemp + = "-"; strtemp + = M_strname;co ut<<strtemp<<endl;}}; Class Composite:public component{private:vector<component*> M_component;public:composite (string strName): Component (strName) {}virtual void Add (component* com) {m_component.push_back (COM);} virtual void Display (int ndepth) {string strtemp;for (int i = 0; i < ndepth; i + +) strtemp + = "-"; strtemp + = M_strname;co Ut<<strtemp<<endl;vector<component*>::iterator p = m_component.begin (); while (P! = M_component.end()) {(*p)->display (ndepth + 2);p ++;}}};/ /clientint Main () {composite* p = new Composite ("Xiao Wang");p->add (New Leaf ("Xiao Li");p->add ("Xiao Zhao"); composite* P1 = new Composite ("Small Five");p 1->add (New Leaf ("Junior"));p->add (p1);p->display (1);/* result-Xiao Wang---Xiao li---xiao Zhao---small five-----junior */return 0;}

Demo Sample Code 2:

#include <iostream> #include <string> #include <vector>using namespace Std;class company{protected: String M_strname;public:company (String strName) {m_strname = StrName;} virtual void Add (company* c) = 0;virtual void Display (int ndepth) = 0;virtual void lineofduty () = 0;}; Class Concretecompany:public company{private:vector<company*> M_company;public:concretecompany (string StrName): Company (strName) {}virtual void Add (company* c) {m_company.push_back (c);} virtual void Display (int ndepth) {string strtemp;for (int i = 0; i < ndepth; i + +) strtemp + = "-"; strtemp + = M_strname;co Ut<<strtemp<<endl;vector<company*>::iterator p = m_company.begin (); while (P! = M_company.end ()) {(* p)->display (ndepth + 1);p + +;}} virtual void Lineofduty () {Vector<company*>::iterator p = m_company.begin (); while (P! = M_company.end ()) {(*p)- >lineofduty ();p + +;}}; Class Hrdepartment:public Company{public:hrdepartment (String strname): Company (strname) {}virtual voidDisplay (int ndepth) {string strtemp;for (int i = 0; i < ndepth; i + +) strtemp + = "-"; strtemp + = M_strname;cout<<str Temp<<endl;} virtual void Add (company* c) {cout<< "error" &LT;&LT;ENDL;} virtual void Lineofduty () {cout<<m_strname<< ": Recruiting talent" <<endl;}};/ /clientint Main () {concretecompany* p = new Concretecompany ("Tsinghua University");p->add (New Hrdepartment ("Tsinghua University talent Department"); concretecompany* P1 = new Concretecompany ("Mathematics department");; P1->add (New Hrdepartment ("Department of Mathematics)"); concretecompany* P2 = new Concretecompany ("Physics Department");p 2->add (New Hrdepartment ("Faculty of Physics");p->add (p1);p->add (p2) ;p->display (1);p->lineofduty ();/* result-Tsinghua University--Tsinghua University--Department of Mathematics Department---Department of Mathematics Department--Department of Physics Department of---Physics Dept. of Human Resources Tsinghua University: Recruitment Talent Department of Mathematics Department: Recruitment Talent Department of Physics Department: recruitment talent */return 0;

Demo Sample Code 3:

Component.h:

#ifndef _component_h_#define _component_h_class component{public:component (); virtual ~component ();p ublic:virtual void operation () = 0;virtual void Add (const component&); virtual void Remove (const component&); Virtual component* Getchild (int);p rotected:private:}; #endif//~_component_h_

Component.cpp:

#include "Component.h" component::component () {}component::~component () {}void component::add (const component&) { }component* component::getchild (int index) {return 0;} void component::remove (const component& com) {}

Composite.h:

#ifndef _composite_h_#define _composite_h_#include "Component.h" #include <vector>using namespace Std;class Composite:public component{public:composite (); ~composite ();p ublic:void operation (); void Add (component* com); void Remove (component* com); component* getchild (int index);p rotected:private:vector<component*> Comvec;}; #endif//~_composite_h_

Composite.cpp:

#include "Composite.h" #include "Component.h" #define NULL 0//define null pointorcomposite::composite () {//vector< Component*>::iterator itend = Comvec.begin ();} Composite::~composite () {}void composite::operation () {Vector<component*>::iterator comIter = ComVec.begin (); for (; Comiter! = Comvec.end (); Comiter + +) (*comiter)->operation ();} void Composite::add (component* com) {comvec.push_back (COM);} void Composite::remove (component* com) {//comvec.erase (&com);} component* composite::getchild (int index) {return comvec[index];}

Leaf.h:

#ifndef _leaf_h_#define _leaf_h_#include "Component.h" Class Leaf:public component{public:leaf (); ~leaf (); void Operation ();p rotected:private:}; #endif//~_leaf_h_


Leaf.cpp:

#include "Leaf.h" #include <iostream>using namespace std; Leaf::leaf () {}leaf::~leaf () {}void leaf::operation () {cout<< "Leaf operation ..." <<ENDL;}

Main.cpp:

#include "Component.h" #include "Composite.h" #include "Leaf.h" #include <iostream>using namespace Std;int main () { leaf* L = new Leaf (); L->operation (); composite* com = new Composite (); Com->add (L); com->operation (); component* ll = com->getchild (0); ll->operation ();/*resultleaf operation ... Leaf operation ... Leaf operation ... */return 0;}

Combo Mode structure diagram:


References:

1, "Big talk design mode C + +"

2, "design pattern refinement----GoF23 design mode Analysis"

3. Design pattern----The basis of reusable object oriented software


Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Design pattern combination mode (Composite) essence

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.