The 23 GOF design modes are generally divided into three categories: Creation Mode, structure mode, and behavior mode.
The Creation Mode abstracts the instantiation process, which helps a system to create, combine, and express its objects independently. A class creation mode uses inheritance to change the class to be instantiated, while an object Creation Mode delegates the Instantiation to another object. The creation mode has two main themes. First, they all encapsulate information about the specific classes used by the system. Second, they hide how instances of these classes are created and put together. All objects in the system know interfaces defined by abstract classes. Therefore, the Creation Mode gives great flexibility in what is created, who creates it, how it is created, and when it is created. They allow you to configure a system with "product" objects with very different structures and functions. The configuration can be static (specified during compilation) or dynamic (at runtime ).
The schema involves how to combine classes and objects to obtain a larger structure. The structure class mode uses an Inheritance Mechanism to combine interfaces or implementations. The structured object mode not combines interfaces and implementations, but describes how to combine some objects to implement new functions. Because the object composite relationship can be changed at runtime, the object composite method has more flexibility, and this mechanism is impossible to achieve with static class composite.
The behavior pattern involves the assignment of duties between algorithms and objects. The behavior pattern not only describes the object or class pattern, but also describes the communication pattern between them. These modes depict complex control flows that are difficult to trace during runtime. They shift users' attention from the control flow to the contact information between objects. The behavior class mode uses the Inheritance Mechanism to distribute actions among classes. Behavior object mode uses Object combination instead of inheritance. Some behavior object modes describe how peer-to-peer objects collaborate to complete tasks that cannot be completed independently by any object.
The creation mode includes: 1. FactoryMethod (Factory method mode); 2. Abstract Factory (Abstract Factory mode); 3. Singleton (Singleton mode); 4. Builder mode and Builder mode ); 5. Prototype (Prototype ).
Structural modes include: 6. Bridge (Bridge Mode); 7. Adapter (Adapter mode); 8. Decorator (decoration mode); 9. Composite (combination mode ); 10. Flyweight (metadata mode); 11. Facade (appearance mode); 12. Proxy mode ).
Behavior patterns include: 13. TemplateMethod (template method mode); 14. Strategy (Policy mode); 15. State (State mode); 16. Observer (Observer mode ); 17. Memento (memorandum mode); 18. Mediator (intermediary mode); 19. Command (Command mode); 20. Visitor (Visitor mode ); 21. Chain of Responsibility (responsible Chain mode); 22. Iterator (Iterator mode); 23. Interpreter (Interpreter mode ).
Factory Method: Defines an interface for creating objects, so that the subclass determines which class to instantiate. Factory Method delays the instantiation of a class to its subclass.
Abstract Factory: Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
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 different representations can be created during the same construction process.
Prototype: Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.
Bridge: Separates abstract parts from their implementations so that they can all change independently.
Adapter: Converts an interface of a class to another interface that the customer wants. The Adapter mode allows the classes that cannot work together due to incompatibility of interfaces to work together.
Decorator: Dynamically add some additional responsibilities to an object. In terms of extended functions, the Decorator mode is more flexible than the subclass generation method.
Composite: Combine objects into a tree structure to represent the "part-whole" hierarchy. Composite makes the customer's use of a single object and Composite object consistent.
Flyweight: Use the sharing technology to effectively support a large number of fine-grained objects.
Facade: Provides a consistent interface for a group of interfaces in the subsystem. The Facade mode defines a high-level interface, which makes the subsystem easier to use.
Proxy: Provides a proxy for other objects to control access to this object.
Template Method: Defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The Template Method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
Strategy: Define a series of algorithms, encapsulate them one by one, and make them replaceable. This mode makes the algorithm changes independent of the customers who use it.
State: Allows an object to change its behavior when its internal state changes. The object seems to have modified its class.
Observer: Defines a one-to-many dependency between objects, so that when the status of an object changes, all objects dependent on it will be notified and automatically refreshed.
Memento: Capture the internal state of an object without compromising encapsulation, and save the state outside the object. In this way, the object can be restored to the Saved state.
Mediator: Encapsulate a series of object interactions with an intermediary object. The intermediary makes the objects do not need to be explicitly referenced to each other, so that the coupling is loose and the interaction between them can be changed independently.
Command: Encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support cancelable operations.
Visitor: Indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the classes of each element.
Chain of Responsibility: To remove the coupling between the request sender and receiver, multiple objects have the opportunity to process the request. Connect these objects into a chain and pass the request along the chain until an object processes it.
Iterator: Provides a method to access each element in an aggregate object sequentially without exposing the internal representation of the object.
Interpreter: For a given language, define a representation of its syntax and define an interpreter that uses this representation to interpret sentences in the language.
Composite: (1) Intention: Combine objects into a tree structure to represent the "part-whole" hierarchy. Composite makes the use of a single object and a Composite object consistent.
(2) Applicability: A. The part of the object you want to represent-the overall hierarchy; B. You want the user to ignore the differences between the composite object and A single object, the user will use all objects in the composite structure in a unified manner.
(3) Advantages and Disadvantages: A. defines class hierarchies that contain basic objects and composite objects: basic objects can be combined into more complex composite objects, and this composite object can be combined, so that the recursion continues. In customer code, you can use composite objects wherever basic objects are used. B. Simplified Customer Code: customers can use the combination structure and a single object in a consistent manner. Generally, users do not know (or care about) whether a leaf node is processed or a composite component. This simplifies the customer code, because in the classes that define the combination, you do not need to write some functions that are filled with selection statements. C. Make it easier to add new types of components: the newly defined Composite or Leaf subclass automatically works with existing structures and customer code, the customer program does not need to be changed because of the new Component class. D. Make your design more general: Sometimes you want a combination to have only some specific components. When using Composite, you must check the runtime instead of depending on the type system to apply these constraints.
(4) Note: A. displayed parent part reference: Keep the reference from child to parent parts to simplify the traversal and Management of the combination structure. Parent Part references can simplify structure migration and delete components, and also support Chain of Responsibility. B. Shared components: Shared components are very useful. For example, they can reduce storage requirements. However, when a component has only one parent component, it is difficult to share the component. C. Maximize Component Interface: one of the purposes of the Composite mode is to make users do not know the specific Leaf and Composite classes they are using. To achieve this goal, the Composite class should define as many public operations as possible for the Leaf and Composite classes. The Composite class generally provides default implementations for these operations, and the Leaf and Composite subclass can redefine them. D. Declare and Manage Sub-parts. E. Should Component implement a Component list: you may want to define the subnode set as an instance variable in the Component class, this Component class also declares some operations to access and manage child nodes. However, storing subclass pointers in the base class results in a waste of space for leaf nodes because leaf nodes do not have subnodes. This method is worth using only when the number of child classes in this structure is relatively small. F. Subpart sorting: If you need to consider the subnode sequence, you must carefully design the access and management interfaces for the subnode to manage the subnode sequence. The Iterator mode provides some guidance in this regard. G. use high-speed buffer storage to improve performance: If you need to frequently traverse or search a combination, the Composite class can buffer the storage to traverse its subnodes or find relevant information. H. Who should delete Component: In a language without a garbage collection mechanism, when a Composite is destroyed, it is recommended that Composite delete its subnodes. Except in one case, the Leaf object does not change and can be shared. I. What kind of data structure is better for storage components? Composite can use multiple data structures to store their subnodes, including connection lists, trees, arrays, and hash tables. Data structure selection depends on efficiency. In fact, using a common data structure is not necessary at all. Sometimes, for each subnode, Composite has a variable corresponding to it, which requires that each subclass of Composite must implement its own management interface.
(5) related mode: A. Normally, the component-parent component connection is used in the Responsibilityof Chain mode. B. the Decorator mode is often used with the Composite mode. When decoration and combination are used together, they usually have a common parent class. Therefore, decoration must support the Component interfaces with Add, Remove, and GetChild operations. C. Flyweight allows you to share components, but you can no longer reference their parent components. D. Iterator can be used to traverse the operations and behavior localization that Composite. E and Visitor should have been distributed in the Composite and Leaf classes.
One problem with the implementation of the Composite mode is to provide a management policy for the sub-node (Leaf), which can be implemented in the following ways: vector, array, linked list, and Hash table.
The Composite mode has a structure similar to the Decorator mode, but the Composite mode is designed to construct classes. The Decorator mode focuses on adding roles to objects without generating child classes. The Decorator mode focuses on modification, while the Composite mode focuses on representation.
Sample Code 1:
# Include
# Include
# Include
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 <"leaf can't add" <
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; cout <
<
: Iterator p = m_component.begin (); while (p! = M_component.end () {(* p)-> Display (nDepth + 2); p ++ ;}}; // client int main () {Composite * p = new Composite ("Xiao Wang"); p-> Add (new Leaf ("Xiao Li ")); p-> Add (new Leaf ("Xiao Zhao"); Composite * p1 = new Composite ("Xiao Wu "); p1-> Add (new Leaf (""); p-> Add (p1); p-> Display (1 ); /* result-Xiao Wang --- Xiao Li --- Xiao Zhao --- Xiao Wu ----- junior year */return 0 ;}
<
Sample Code 2:
# Include
# Include
# Include
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
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; cout <
<
: Iterator p = m_company.begin (); while (p! = M_company.end () {(* p)-> Display (nDepth + 1); p ++ ;}} virtual void LineOfDuty () {vector
: Iterator p = m_company.begin (); while (p! = M_company.end () {(* p)-> LineOfDuty (); p ++ ;}}; class HrDepartment: public Company {public: HrDepartment (string strname ): company (strname) {} virtual void Display (int nDepth) {string strtemp; for (int I = 0; I <nDepth; I ++) strtemp + = "-"; strtemp + = m_strName; cout <
<
Add (new HrDepartment ("talent department of Tsinghua University"); ConcreteCompany * p1 = new ConcreteCompany ("Mathematics Department ");; p1-> Add (new HrDepartment ("Department of mathematics"); ConcreteCompany * p2 = new ConcreteCompany ("Department of Physics "); p2-> Add (new HrDepartment ("Department of Physics talent"); p-> Add (p1); p-> Add (p2); p-> Display (1 ); p-> LineOfDuty ();/* result-Tsinghua University-talent department of Tsinghua University-Department of mathematics-Department of Physics talent department of Tsinghua University: recruitment of talent department of mathematics: talent Recruitment Department of the physics department: Talent Recruitment */return 0 ;}
<
<
Sample Code 3:
Component. h:
#ifndef _COMPONENT_H_#define _COMPONENT_H_class Component{public:Component();virtual ~Component();public:virtual void Operation() = 0;virtual void Add(const Component&);virtual void Remove(const Component&);virtual Component* GetChild(int);protected: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
using namespace std;class Composite : public Component{public:Composite();~Composite();public:void Operation();void Add(Component* com);void Remove(Component* com);Component* GetChild(int index);protected:private:vector
comVec;};#endif//~_COMPOSITE_H_
Composite. cpp:
#include "Composite.h"#include "Component.h"#define NULL 0 //define NULL POINTORComposite::Composite(){//vector
::iterator itend = comVec.begin();}Composite::~Composite(){}void Composite::Operation(){vector
::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:
#include "Composite.h"#include "Component.h"#define NULL 0 //define NULL POINTORComposite::Composite(){//vector
::iterator itend = comVec.begin();}Composite::~Composite(){}void Composite::Operation(){vector
::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. cpp:
# Include "Leaf. h" # include
Using namespace std; Leaf: Leaf () {} Leaf ::~ Leaf () {} void Leaf: Operation () {cout <"Leaf Operation..." <
< pre>
Main. cpp:
#include "Component.h"#include "Composite.h"#include "Leaf.h"#include
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;}
Combined Mode Structure:
References:
1. Big talk Design Model C ++
2. Design Patterns-Analysis of GoF23 Design Patterns
3. Design Patterns-Basics of reusable Object-Oriented Software
<>