C ++/Design Mode

Source: Internet
Author: User

C ++/design mode (23:05:39)

[There are 10 people in the world who understand binary and binary .]

 
Definition

Design pattern is a set of summary of code design experiences that are repeatedly used, known to most people, classified and catalogued. The design pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability.

There is no doubt that the design model is a win-win solution for others and the system. The design model enables code compilation to be truly engineered. The design model is the foundation of software engineering, just like the building blocks.

Gof's design patterns (published in 1995) is the first time that it has elevated the design patterns to the theoretical level by gamma, Helm, Johnson & vlissides, and Addison-Wesley, in addition, this book proposes 23 basic design patterns. Since then, a large number of new design patterns have emerged in the development process of reusable object-oriented software.

 

Design Pattern and framework

Currently, reusable object-oriented software systems are generally divided into two categories: application toolbox and framework. The specific software we usually develop is an application program, and Java APIs are a toolbox; the framework is a group of collaborative classes that constitute a type of reusable design for specific software. EJB is the framework that Java applies to enterprise computing.

The framework usually defines design parameters such as the relationship between the overall structure class and object of the application system, so that specific application implementers can focus on specific details of the application. The framework mainly records the common design decisions in software applications, and emphasizes design reuse. Therefore, the design model must be used in the framework design.

In addition, the design patterns help you understand the framework structure. Mature frameworks usually use multiple design patterns. If you are familiar with these design patterns, you will no doubt be able to quickly master the structure of the Framework, if developers suddenly come into contact with ejbj2ee and other frameworks, they will feel particularly difficult to learn and master. Instead, they will first master the design mode, which is undoubtedly a powerful tool for you to analyze the EJB or J2EE system.

 

Principles of design patterns

In recent years, everyone has begun to pay attention to the design model. So why should we use the design pattern? Why are so many design patterns designed? To be honest, I have never figured it out before. It's just a look at everyone's "design pattern", and the heart is a bit weak. So I bought the design model of the "four-person gang". The results showed that I understood it clearly. I forgot it after a while. It may be because I am relatively "stupid" :)) recently, I have some insights. "Joy is better than joy". I 'd like to share it with you and hope to give you some advice!

Why do we advocate "Design Pattern? The root cause is to reuse code and increase maintainability. So how can we achieve code reuse? OO has several principles of its predecessors: "open-closed" principle (open closed principal), Rishi replacement principle, and synthetic Reuse Principle. The design pattern is to achieve these principles, so as to achieve code reuse and increase maintainability.

1. "Open-Close" Principle

This principle was proposed by "Bertrand Meyer. Original article: "software entities shocould be open for extension, but closed for modification ". That is to say, the module should be open for expansion, but closed for modification. The module should be extended without modifying the original (original) code. How can we scale it out? Let's look at the factory model "factory pattern": Suppose Zhongguancun has a hacker who sells pirated disk and wool film. We designed a "CD sales management software" for him ". We should first design a "cd" interface.

[Pre] ______________

| <> |

| Cd |

| _____________ |

| + Sell () |

|

| _____________ | [/PRE]

The pirated disk and the wool film are its sub-categories. The kid manages these CDs through "discfactory. Code:

Public class discfactory {

Public static disc getdisc (Java/lang/string.java.html "target =" _ blank "> string name ){

Return (CD) Java/lang/class.java.html "target =" _ blank "> class. forname (name). getinstance ();

}

}

How can someone buy a pirated disk?

Public class kiddies {

Public static void main (Java/lang/string.java.html "target =" _ blank "> string [] ARGs ){

CD d = discfactory. getdisc ("pirated disk ");

CD. Sell ();

}

}

If one day, this kid finds his conscience and starts selling genuine software. It doesn't matter. We just need to create another sub-category "genuine software" of "cd. You do not need to modify the original structure and code. How is it? For extension development, disable modification. "Open-closed principle"

The factory model is to expand specific products. Some projects may require more scalability. To expand the "Factory", it becomes an "Abstract Factory model ".

2. Lee's replacement principle

The Li's replacement principle was proposed by "Barbara liskov. If the parent class is called, the sub-classes can be fully run. For example:

CD d = new pirated disk ();

D. Sell ();

Now I want to change the category of "pirated disk" to "fake disk". No problem, it can be fully run. The Java compiler checks whether the program complies with the Li's replacement principle. Do you still remember a principle inherited by Java? The access permission of the subclass override method cannot be less than that of the method corresponding to the parent class. For example, if the "sell" access permission in the "cd" method is "public", then the "sell" method in "pirated disk" and "Mao film" cannot be "protected" or "private", and compilation cannot pass. Why? You think: if the "selling" method of "pirated disk" is private. The following code cannot be executed:

CD d = new pirated disk ();

D. Sell ();

It can be said that the Li's replacement principle is a basis for inheritance reuse.

3. Principles of merging and reuse

That is to say, we need to use less inheritance and more synthesis relationships. I once wrote a program like this: There are several classes that need to deal with the database, so I wrote a database operation class, and other classes dealing with the database inherit this class. As a result, I modified a method of the database operation class, and each class needs to be modified. "Pull your whole body "! Object-oriented is to limit fluctuations to the smallest possible range.

In Java, you should try to program interfaces instead of implementing classes. In this way, changing the subclass does not affect the code that calls its method. We need to keep every category in touch with others as little as possible, "Don't talk to strangers ". In this way, the fire in the city will not affect the fish in the pool. Scalability and maintainability can be improved

After understanding these principles, let's look at the design model, just how to implement these principles on specific issues. Zhang Wuji learned Taijiquan. He forgot all his tricks and knocked down Xuan Mi, the so-called "No tricks in his mind ". The design pattern can be described as a trick. If you learn all kinds of patterns first, and forget all the patterns and do what you want, it can be described as the highest level of OO. Haha, funny, funny! (JR)

4. Dependency reversal Principle

Abstraction should not be dependent on details, but details should be dependent and abstract.

Programming for interfaces, rather than implementing programming.

PASS Parameters, or reference classes with high levels as much as possible in composite aggregation relationships.

We can dynamically create various specific objects when constructing objects. Of course, if some specific classes are stable, you do not have to create an abstract class as its parent class, this gives you the feeling of tongue-filling.

5 interface isolation principles

In the example of customized services, each interface should be a role, not many, and should not do anything that should not be done.

6 abstract classes

The abstract class does not have instances. It is generally inherited as a Child class of the parent class and generally contains the common attributes and methods of this series.

Note: In a good inheritance relationship, only leaf nodes are specific classes, and other nodes should be abstract classes, that is, specific classes

Is not inherited. Put as much common code as possible into the abstract class.

7 dumit's Law

Minimum knowledge principle. Do not talk to strangers.

 

Four basic elements of a model

The design pattern allows people to reuse the successful design and architecture more easily and easily. Expressing proven technologies into design patterns makes it easier for new system developers to understand their design ideas.

1. Pattern name)

It uses one or two words to describe the model's problems, solutions, and effects. Naming a new pattern adds our design vocabulary. The design pattern allows us to design at a higher abstraction level. Based on a schema vocabulary, we can discuss patterns between ourselves and our colleagues and use them when writing documents. The model name can help us think about it, so that we can exchange design ideas and design results with others. Finding the proper pattern name is also one of the difficulties in designing pattern cataloguing.

2. Question (problem)

Describes when to use the mode. It explains the causes and consequences of design problems, and may describe specific design problems, such as how to use objects to represent algorithms. It may also describe the class or object structure that leads to inflexible design. Sometimes, the problem part includes a series of prerequisites that must be met by the usage mode.

3. Solution)

Describes the components of the design, the relationship between them, their respective responsibilities and collaboration methods. Because a pattern is like a template and can be used in many different scenarios, the solution does not describe a specific and specific design or implementation, instead, it provides an abstract description of the design problem and how to use a combination of general elements (class or object combination) to solve the problem.

4. effect (consequences)

Describes the effect of the model application and the balance between the use mode. Although we do not always mention pattern effects when describing design decisions, they are important for evaluating design choices and understanding the cost and benefits of patterns. Most of the software results focus on measuring time and space. They also express language and implementation problems. Because reuse is one of the elements of object-oriented design, the pattern effect includes its impact on system flexibility, scalability, or portability, listing these effects explicitly is helpful for understanding and evaluating these patterns.

//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////
1. c ++/factory for design patterns (23:56:10)

Factory chasing mm is a must-have dinner. Both the chicken wings of McDonald's and the chicken wings of KFC are what mm loves. Although the taste is different, whether you take mm to McDonald's or KFC, just say "four chicken wings" to the waiter. McDonald's and KFC are factories that produce chicken wings.

Factory model: the customer class and the factory class are separated. A consumer needs a product at any time and only requests from the factory. Consumers can accept new products without modification. The disadvantage is that the factory class must be modified when the product is modified. For example, how to create and provide data to clients.

 

// Product. h
# Ifndef _ product_h _
# DEFINE _ product_h _
Class Product
{
Public:
Virtual ~ Product () = 0;
Protected:
Product ();
PRIVATE:
};
Class concreteproduct: Public Product
{
Public:
~ Concreteproduct ();
Concreteproduct ();
Protected:
PRIVATE:
};
# Endif

// Product. cpp
# Include "product. H"
# Include <iostream>
Using namespace STD;
Product: product ()
{
}
Product ::~ Product ()
{
}
Concreteproduct: concreteproduct ()
{
Cout <"concreteproduct..." <Endl;
}
Concreteproduct ::~ Concreteproduct ()
{
}

 

// Factory. h

# Ifndef _ factory_h _

# DEFINE _ factory_h _

Class product;

Class Factory

{

Public:

Virtual ~ Factory () = 0;

Virtual Product * createproduct () = 0;

Protected:

Factory ();

PRIVATE:

};

Class concretefactory: Public Factory

{

Public:

~ Concretefactory ();

Concretefactory ();

Product * createproduct ();

Protected:

PRIVATE:

};

# Endif

 

// Factory. cpp

# Include "factory. H"

# Include "product. H"

 

# Include <iostream>

Using namespace STD;

Factory: Factory ()

{

}

Factory ::~ Factory ()

{

}

Concretefactory: concretefactory ()

{

Cout <"concretefactory..." <Endl;

}

Concretefactory ::~ Concretefactory ()

{

}

Product * concretefactory: createproduct ()

{

Return new concreteproduct ();

}

 

// Main. cpp

# Include "factory. H"

# Include "product. H"

# Include <iostream>

Using namespace STD;

Int main (INT argc, char * argv [])

{

Factory * FAC = new concretefactory ();

Product * P = fac-> createproduct ();

Return 0;

}

//////////////////////////////////////// //////////////////////////////////////// ///////////////////////
2. c ++/Builder (23:58:24)

Builder mm is listening to the phrase "I Love You". When you see mm in different places, you must be able to say this to her in their dialects, I have a multi-language translation machine with a key for each language above. To see mm, I only need to press the corresponding key, it will be able to say "I love you" in the appropriate language, and foreign mm can also easily develop, This is my "I love you" construction mode. (This must be better than the US military's translation server in Iraq)

Construction mode: separates the internal appearance of a product from the product generation process, so that a building process generates product objects with different internal appearances. The construction mode allows the product's internal appearance to change independently, so that the customer does not have to know the details of the product's internal composition. The construction model enforces a step-by-step construction process.

 

3. c ++/factory method (00:00:08)

Factory method ask mm to go to McDonald's for a hamburger. Different mm has different tastes. Remember that it is an annoying thing. I usually use this mode and take the mm to the waiter, say "I want a hamburger". What kind of hamburger do I need? Just let mm talk to the waiter directly.

Factory method mode: the Core factory category is no longer responsible for the creation of all products. Instead, it submits the specific creation work to the subclass to become an abstract factory role, it is only responsible for providing the interface that must be implemented by a specific factory class, without touching the details of which product class should be instantiated.

4. c ++/original model mode (prototype) (00:02:24)

Prototype is used to chat with MM via QQ. It must be said with some affectionate words. I have collected a lot of emotional words, and I just need to copy them out and put them in QQ, this is my prototype. (100 yuan a copy, do you want)
Original Model mode: specify the type of the object to be created by giving a prototype object, and then create more objects of the same type by copying the prototype object. The original model mode allows you to dynamically add or remove product classes. The product class does not need to have any predefined level structure. The original model mode applies to any level structure. The disadvantage is that each class must have a clone method.

5. c ++/Singleton (00:09:32)

Singleton has six beautiful wives. Their Husbands are me. I am sigleton, our family's husband. All they need to say is "husband, that's me (I had a dream just now. How can this be a good thing)

Singleton mode: Singleton mode ensures that a class has only one instance, and instantiate the instance and provides the singleton mode to the entire system. The Singleton mode can only be used when there is a real "Single Instance" demand.

6. C ++/adapter (transformer) mode (00:10:48)

Adapter met Sarah, a beautiful girl from Hong Kong at a friend's party, but she could not speak Cantonese or Mandarin, so she had to turn to my friend Kent, as an adapter between me and Sarah, Sarah and I can talk to each other (I don't know if he will play with me)

Adapter (transformer) mode: converts an interface of a class into another interface that the client expects, so that the two classes that cannot work together due to interface mismatch can work together. The adaptation class can return a suitable instance to the client based on the parameters.

7. c ++/Bridge Mode (00:11:45)

Bridge met mm in the morning, saying good morning, meeting mm in the evening, saying good evening; meeting mm wearing a new dress, saying that your clothes are so beautiful, meeting MM's new hair style, say your hair looks pretty. Don't ask me the question "How to say mm has a new hairstyle in the morning". Just use bridge to combine it.

Bridge Mode: Abstraction and implementation are decoupled so that the two can change independently, that is, the strong association between them becomes weak Association, that is, the combination/aggregation relationship is used between the abstraction and implementation of a software system, rather than the inheritance relationship, so that the two can change independently.

8. C ++/composite mode (00:12:48)

Composite Mary has a birthday today. "You want to give me a gift for my birthday ." "Well, all right, go to the store and pick it for yourself ." "This T-shirt is very beautiful. Buy it. This dress looks good. Buy it. This bag is also good. Buy it ." "Hey, I bought three items. I only promised to give one gift ." "What, T-shirts and skirts and bags, just like a set, miss, please pack it. "……", Mm will all use the composite mode. Will you?

Merging mode: the merging mode organizes objects into the tree structure and can be used to describe the relationship between the whole and the part. The merging mode is a tree structure mode for processing objects. The merging mode shows the relationship between the part and the whole in a tree structure. The merging mode allows the client to view individual component objects in the same way as the compositing objects composed of them.

9. c ++/decorator (00:13:53)

Decorator Mary should not ask her to pick her up after her birthday, or she will definitely finish the meal this month. She took out the photo I took on the top of Huashan last year and wrote "the best gift" on the back, I love your FITA. "I went to the gift shop on the street and bought an image frame (the mm for selling gifts is also very beautiful ), mike, who is next door to art design, designed a beautiful box and installed it ......, We are all decorator, and we are all modifying this person. How do you understand this?

Decoration mode: The decoration mode extends the object functions in a transparent way to the client. It is an alternative to the inheritance relationship and provides more flexibility than inheritance. Dynamically adds features to an object, which can be dynamically revoked. A large number of functions are generated by the arrangement and combination of some basic functions.

10. c ++/facade (00:15:41)

Facade I have a professional Nikon camera. I like to adjust the aperture and shutter manually, so that only the photos taken are professional, but mm doesn't understand this. It won't take me for a long time. Fortunately, the camera has a facade design mode, which allows you to adjust the camera to the automatic file. You only need to aim at the target and press the shutter. Everything is automatically adjusted by the camera, in this way, mm can also use this camera to take a photo for me.

Facade mode: external communication with a sub-system must be performed through a unified facade object. The facade mode provides a high-level interface to make subsystems easier to use. Each subsystem has only one portal class, and this portal class has only one instance, that is, it is a singleton mode. However, the entire system can have multiple portals.

11. c ++/flyweight (00:17:35)

Flyweight sends text messages to mm every day, and his fingers are exhausted. Recently, he bought a new mobile phone. He can put some commonly used sentences in his mobile phone. When using the text, he can take them out directly, add the MM name to the front and you will be able to send the message without a single word. The shared sentence is flyweight, And the MM name is the extracted external feature, which is used according to the context.

Enjoy mode: flyweight is the most lightweight in boxing. The metadata mode efficiently supports a large number of fine-grained objects in a shared manner. The key to the sharing mode is to distinguish between the internal and external states. The internal status is stored in the shared element and will not change with the environment. The external state changes with the change of the environment. The external status cannot affect the internal status. They are independent of each other. The States that can be shared and those that cannot be shared are separated from the conventional classes to remove the States that cannot be shared from the classes. The client cannot directly create shared objects, but should use a factory object to create shared objects. The metadata mode greatly reduces the number of objects in the memory.

12. c ++/Proxy mode (00:18:29)

Proxy and mm chat online, always starting with "hi, hello", "Where are you from ?" "How old are you ?" "How tall ?" These words are really annoying. Write a program as my proxy. When I receive these words, I have set up an automatic answer. When I receive other words, I will be notified of the answer, cool.

Proxy mode: the proxy mode provides a proxy object for an object and controls the reference to the source object. An agent is an action taken by one person or institution on behalf of another person or institution. In some cases, the customer does not want or cannot directly reference an object. The proxy object can serve as an intermediary between the customer and the target object. The client cannot identify the proxy topic object and the real topic object. The proxy mode does not know the real proxy object, but only holds an interface of the proxy object. At this time, the proxy object cannot be created as the proxy object, the proxy object must have other roles created and passed in on behalf of the system.

13. c ++/chain of responsible (00:19:31)

Chain of responsibleity went to English classes at night. In order to have a good time, he sat down in the last row. Wow, there were several beautiful mm in front. He found a piece of paper and wrote "Hi, can I be my girlfriend? If you don't want to, please pass it to the front. The paper is uploaded one by one. Unfortunately, the mm in the first row passed the paper to the teacher. I heard it was an old virgin. Run fast!

Responsibility Chain Mode: In the responsibility chain mode, many objects are connected by the reference of each object to its next home to form a chain. Requests are transmitted on this chain until an object on the chain decides to process this request. The customer does not know which object on the chain finally processes this request. The system can dynamically reorganize the chain and assign responsibility without affecting the client. The handler has two options: Take responsibility or push the responsibility to the next house. A request cannot be accepted by any receiving end object.

14. c ++/command mode in design mode (00:20:58)

Command an MM family was very strict and couldn't meet each other. She had to use her brother to send messages between us. She gave me some instructions and wrote a piece of paper for her brother to bring me. No, her brother sent another command. To thank him, I asked him to eat a bowl of soy sauce. He said, "I also sent command to my sister and three boyfriends, you are the least angry to ask me to eat noodles."

Command mode: The command mode encapsulates a request or operation into an object. The command mode separates the responsibility for issuing commands from the responsibility for executing commands and delegates them to different objects. In command mode, the requester and the sender are allowed to be independent, so that the requester does not have to know the interfaces of the receiver, how the request is received, and whether the operation is executed, when and how it is executed. The system supports command revocation.

15. c ++/design mode-interpreter mode (00:22:22)

Interpreter has a "bubble mm Sutra", which has various tips on bubble mm, such as the steps to eat western food and the methods to watch movies. When dating with MM, you only need to create an interpreter, run the script above.

Interpreter mode: Given a language, the interpreter mode can define a representation of its syntax and provide an interpreter at the same time. The client can use this interpreter to explain sentences in this language. The interpreter mode describes how to explain these statements with a simple syntax. The language mentioned in the interpreter mode refers to any combination that any interpreter object can interpret. In the interpreter mode, you need to define a hierarchical structure of a command class that represents grammar, that is, a series of combination rules. Each command object has an interpretation method, which represents an interpretation of the command object. Any permutation and combination of objects in the hierarchical structure of command objects is a language.

16. c ++/iteration submode (iterator) (00:23:22)

Iterator I fell in love with Mary and proposed to her desperately.

Mary: "If I want to marry you, I have to agree to my conditions"

Me: "I agree with all the conditions. Let's talk about it"

Mary: "I saw the 1 karat diamond"

Me: "I bought, I bought, are there any other products ?"

Mary: "I saw the villa by the lake"

Me: "I bought, I bought, are there any other products ?"

Mary: "I saw that Ferrari sports car"

I sat down in a chair and bit my teeth: "I bought it, I bought it, do you still have it ?"

Iteration sub-mode: the iteration sub-mode can sequentially access an element in the aggregation without exposing the internal representation of the aggregation. The aggregation of multiple objects is called aggregation. Clustering objects are container objects that can accommodate a group of objects. The iteration sub-mode encapsulates the iteration logic into an independent sub-object, which is separated from the aggregation itself. The iteration submode simplifies the aggregation interface. Each clustering object can have one or more iteration sub-objects. The iteration status of each iteration sub-object can be independent of each other. The iteration algorithm can be independent from the clustering role changes.

17. c ++/design mode: mediator (00:24:52)

It is unclear who should pay for each other when the mediator is playing mahjong with four mm. Fortunately, I was there, counting the money based on their chips, and getting the money from me, if I lose the money, I will pay it to me. Everything will be OK, And I will receive four mm calls.

Called by mode: The called by mode encapsulates a series of ways in which objects interact, so that these objects do not have to interact explicitly. So that they can be loosely coupled. When the roles of some objects change, the roles of other objects are not immediately affected. Ensure that these functions can be changed independently of each other. The mediator mode converts the multi-to-many interaction into one-to-many interaction. The mediation mode abstracts the behavior and collaboration of objects, and processes the interaction between objects and other objects on a small scale.

18. c ++/memento (00:26:06)
Tags: It classification: C ++/Design Mode

When memento is chatting with several mm at the same time, you must remember what you said to mm just now. Otherwise, MM will be unhappy when it finds out. Fortunately, I have a memorandum, I copied a copy of what I said to the mm and saved it in the memo so that I can view the previous records at any time.

Memorandum mode: A memorandum object is an object used to store snapshots of the internal state of another object. The purpose of the memorandum mode is to catch the state of an object without damaging the encapsulation, and store it externally, in this way, this object can be restored to the stored state when appropriate in the future.

19. c ++/Observer mode (observer) (00:26:59)
Tags: It classification: C ++/Design Mode

Does observer want to know our company's latest mm intelligence? Join the company's mm intelligence contact list. Tom is responsible for collecting intelligence. The new intelligence he found does not need to notify us one by one and is directly released to the contact list. We serve as subscribers (observers) you can receive the information in time.

Observer mode: The Observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

20. c ++/State mode in design mode (00:27:59)
Tags: It classification: C ++/Design Mode

When the State interacts with MM, you must pay attention to her status. In different states, her behavior may be different. For example, if you ask her to go to a movie this evening, if mm is not interested in you, he will say "something is going on". If mm is not so annoying to you but doesn't like it, he will say "okay, but can I bring my colleagues? ", If you like your mm, you will say, "What time is it? How about watching a movie ?", Of course, if you are doing well during a movie, you can also turn the status of mm from dislike to liking.

State mode: State mode allows an object to change its behavior when its internal state changes. This object seems to have changed its class. The state pattern encapsulates the behavior of the studied object in different State objects. Each State object belongs to a subclass of an abstract state class. The intention of the state mode is to change the behavior of an object when its internal state changes. The State mode creates a subclass of the state class for the possible states of each system. When the system status changes, the system changes the selected subclass.

21. c ++/Strategy (00:29:00)
Tags: It classification: C ++/Design Mode

Strategy should use different strategies for dating with different types of MM. Some recommend good movies, some recommend good snacks, and some recommend romantic matches when going to the beach, the single goal is to get the attention of mm. There are a lot of strategy in my pursuit of mm.

Policy mode: the Policy mode encapsulates each algorithm into an independent class with a common interface for a group of algorithms so that they can be replaced with each other. The policy mode allows the algorithm to change without affecting the client. Rule mode separates behavior from environment. The environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in specific policy classes. Because the algorithm and environment are independent, the increase, decrease, and modification of the algorithm will not affect the environment and the client.

22. c ++/template method (00:30:01)
Tags: It classification: C ++/Design Mode

Has template method read the classic article "how to persuade girls to bed? From the process of realizing that a girl goes to bed, there are eight steps (Template Method): encounter, break the deadlock, pursue, kiss, foreplay, start-up, caress, and enter ), however, each step has a different approach for different situations. It depends on your situation (specific implementation ).

Template Method mode: The template method mode prepares an abstract class, implements part of the logic in the form of a specific method and a specific constructor, and then declares some abstract methods to force the subclass to implement the remaining logic. Different sub-classes can implement these abstract methods in different ways to implement the rest logic differently. First, create a top-level logic framework, and leave the logic details to specific sub-classes for implementation.

23. c ++/visitor mode in design mode (visitor) (00:31:02)
Tags: It classification: C ++/Design Mode

Visitor sends a bunch of flowers and a card to each mm on Valentine's Day. However, the flowers sent by every mm are based on her own characteristics, and each card should also be selected based on her own characteristics, I should ask the florist and the gift shop owner for a visitor. Let the florist select a bunch of flowers based on the characteristics of mm and let the gift shop owner select a card based on the characteristics of each person, this makes it much easier.
Visitor mode: the visitor mode aims to encapsulate operations that are applied to certain data structure elements. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged. The visitor mode is suitable for systems with relatively undetermined data structures. It frees the coupling between the data structure and the operations acting on the structure, allowing the operation set to evolve freely. The visitor mode makes it easy to add new operations, that is, to add a new visitor class. In the visitor mode, the related behaviors are concentrated in a visitor object, rather than scattered into node classes. When using the visitor mode, put as many object browsing logic as possible in the visitor class, rather than in its subclass. The visitor mode allows you to access member classes of different hierarchies over the hierarchical structure of several classes.

 

Related Article

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.