Original text: zhuanlan.zhihu.com/p/100746724Copy the code

preface

Design Pattern is a series of routines to solve specific problems. It is not a syntax specification, but a set of solutions to improve code reusability, maintainability, readability, robustness, and security.

Design patterns are often asked in programmer interviews, usually to explain their principles and point out their strengths and weaknesses, or to compare similarities and differences between several similar patterns. A written test may include questions that draw a UML diagram of a design pattern. Just because it’s not a big part of the interview process doesn’t mean it’s not important.

On the contrary, design patterns are very important to programmers. They are the guarantee that we write good programs. Design patterns are closely related to the programmer’s ability to construct and read source code, which is worth studying deeply. Full edition 267 pages of real case study notes on design patterns

1. Factory method

Chase after MM not little please have a meal, McDonald’s chicken wings and KFC chicken wings are MM love to eat things, although the taste is different, but no matter you take MM to McDonald’s or KFC, just say to the waiter “to four chicken wings” on the line. McDonald’s and KFC produce chicken wings in the Factory model: customer class and Factory class are separate.

Any time a consumer needs a product, he simply asks the factory. Consumers can accept the new product without modification. The downside is that when the product changes, the factory class changes accordingly. For example: how to create and provide to the client.

2. Builder mode

MM to hear most is “I love you” this sentence, see different parts of the MM, to be able to use their dialect told her this sentence oh, I have a variety of language translation machine, each language has a button above, I just press the corresponding key see MM, it will be able to use appropriate language to say “I love you” this sentence, The MM of abroad also can be done easily weigh in hand, this is my “I love you” builder.

Construction mode: the internal representation of a product is separated from the product generation process, so that a construction process generates product objects with different internal representation. The construction mode allows the internal appearance of the product to be changed independently without the customer knowing the details of the internal composition of the product. The build model can enforce a step-by-step build process.

3. Abstract factories

Please MM to McDonald’s to eat hamburger, different MM have different taste, it is a boring thing to remember each, I generally use the Factory Method mode, take MM to the waiter there, say “want a hamburger”, specific what kind of hamburger, let MM directly with the waiter to say.

Factory method pattern: The core factory class is no longer responsible for creating all the products, but instead hands over the concrete creation to subclasses, becoming an abstract factory role that gives only the interfaces that the specific factory class must implement, without touching the details of which product class should be instantiated.

4. Prototyping

Chat with MM QQ, must say some of the words of deep feeling, I collected a lot of disgusting words of love, when need, as long as copy comes out to put QQ inside went, this is my love words prototype. (100 yuan each, do you want it?)

The original model pattern: specify the type of 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 pattern allows you to dynamically add or subtract product classes. Product classes do not have to have any predefined hierarchy. The original model pattern applies to any hierarchy. The downside is that each class must be equipped with a clone method.

5. Monomorphic mode

I have six beautiful wives, all of whom are married to me. I am our Sigleton. When they say “husband,” they all mean the same person, me.

Singleton pattern: The singleton pattern ensures that there is only one instance of a class, and it instantiates itself and provides this instance singleton pattern to the entire system. The singleton pattern should only be used when there is a need for a true “single instance.”

6. Adapter mode

I met a beautiful Sarah from Hong Kong at my friend’s party, but I can’t speak Cantonese and she can’t speak Mandarin, so I have to turn to my friend Kent for help. He acts as the Adapter between Sarah and me, so that Sarah and I can talk to each other (I don’t know if he will play me).

Adapter (transformer) pattern: Transforms the interface of one class into another interface expected by the client, thus enabling two classes to work together that would otherwise not work together due to interface mismatches. The adaptation class can return an appropriate instance to the client based on the parameters.

7. Bridge mode

If you meet MM in the morning, say good morning. If you meet MM in the evening, say good evening. Run into MM to wear a new clothes, say your clothes good beautiful oh, run into MM to do a new hairstyle, say your hair good beautiful oh. Don’t ask me “how can I say that I met the woman in the morning with a new hairstyle?

Bridge pattern: Decouple abstraction and realization so that they can change independently, that is, turn their strong relationship into weak relationship, that is, use composition/aggregation relationship rather than inheritance relationship between abstraction and realization of a software system, so that the two can change independently.

8. Synthesis mode

Mary’s birthday is today. “You’re going to give me a present for my birthday.” “Well, all right, go to the store, take your pick.” “This T-shirt is nice, buy it, this skirt is nice, buy it, this bag is nice, buy it.” “Hey, bought three, I only promised to send a gift of oh.” “What ah, T-shirt plus skirt plus bag, just match into a set of ah, young lady, trouble you wrap up.” “……” , MM will use Composite mode, you can not?

Composite pattern: The composite pattern organizes objects into a tree structure that can be used to describe the relationship between whole and part. The composition pattern is a pattern that deals with the tree structure of objects. The composition model represents the relationship between parts and whole in a tree structure. Composition mode allows clients to treat individual component objects as if they were the same as the composite objects they compose.

9. Decoration mode

I took the photo I took on top of Mount Hua last year, wrote on the back, “The best gift is love your Fita”, and then bought a picture frame in the gift shop on the street (the MM selling gifts is also very beautiful). I asked Mike, the art designer next door, to design a beautiful box and put it in it… We’re all decorators, and we all end up decorating me. Okay?

Decorator pattern: Decorator pattern extends the functionality of objects in a transparent way to the client and is an alternative to inheritance, providing more flexibility than inheritance. Adding functionality to an object dynamically can be undone dynamically. Add a very large number of functions from permutations and combinations of basic functions.

10. Facade mode

I have a professional Nikon camera, I like their own manual aperture, shutter, so that the photo is professional, but the MM can not understand these, taught along while also won’t. Fortunately, the camera has a Facade design mode, set the camera to automatic, just aim at the target and press the shutter, everything is automatically adjusted by the camera, so MM can also use this camera to take a picture of me. Facade pattern: External communication with a subsystem must occur through a unified facade object.

Facade mode provides a high-level interface that makes subsystems easier to use. Each subsystem has only one facade class, and this facade class has only one instance, that is, it is a singleton pattern. But the entire system can have multiple facade classes.

11. Enjoy yuan mode

Every day with MM text messages, fingers are tired to death, recently bought a new mobile phone, can put some commonly used sentences exist in the mobile phone, to use the time, take out directly, in front of the name of the MM can be sent, and then need not a word a word to knock. The shared sentence is Flyweight, and the MM name is the extracted external feature, used according to the context. FLYWEIGHT: FLYWEIGHT is the lightest weight in boxing.

The share pattern efficiently supports a large number of fine-grained objects in a shared manner. The key of sharing mode is to distinguish intrinsic state and extrinsic state. Intrinsic state is stored within the element and does not vary with the environment. Externality changes with the environment. The external states cannot affect the internal states, they are independent of each other.

Separate states that can be shared from states that cannot be shared from regular classes, and exclude states that cannot be shared from classes. Instead of creating shared objects directly, clients should use a factory object to create shared objects. The share mode drastically reduces the number of objects in memory.

12. Proxy mode

Chat with MM on the net, always at the beginning “hi, hello”, “where do you come from?” “How old are you?” “How tall is he?” These words, really annoying, write a program as my Proxy bar, all received these words have set up their own answer, received other words and then inform me to answer, how, cool bar.

Proxy mode: The proxy mode provides a proxy object to an object and controls references to source objects. Agency is when a person or agency acts on behalf of another person or agency. In cases where a client does not want or is unable to reference an object directly, a proxy object can act as a direct intermediary between the client and the target object.

The client cannot distinguish the proxy subject object from the real subject object. The proxy mode may not know the real proxied object, but only has an interface of the proxied object. In this case, the proxy object cannot create the proxied object, and the proxied object must be created and passed in by other roles in the system.

13. Chain of responsibility mode

Evening go to top English class, for good escape sit to the last row, wow, front sat several beautiful MM ah, look for a piece of paper, write “Hi, can do my girlfriend? If you don’t want to please to the prequel “, the note on one by one of the pass up, bad, to the first row of MM pass the note to the teacher, HEARD is an old maid ah, run!

Chain of responsibility: In the chain of responsibility pattern, a chain of objects is formed by each object’s reference to its next parent. Requests pass along the chain until one of the objects on the chain decides to process the request. The client does not know which object on the chain ultimately handles the request, and the system can dynamically reorganize the chain and assign responsibilities without affecting the client. The handler has two choices: take the blame or pass it on to the next employer. A request can end up not being accepted by any receiving object.

14. Command mode

The an have a MM in the home tube get particularly strict, can’t meet, have to use her younger brother to transmit information between us, she have what instruction to me, write a piece of paper to let her younger brother bring me. In order to thank him, I invited him to eat a bowl of noodles with mixed sauce. However, he said, “I sent commands to my sister’s three boyfriends at the same time. You are the stingy one who invited me to eat noodles.”

Command mode: Command mode encapsulates a request or operation into an object. The command pattern separates the responsibility for issuing and executing commands and delegates them to different objects. The command pattern allows the requesting party to be separated from the sending party, so that the requesting party does not have to know the interface of the receiving party, much less how the request is received, and whether, when, and how the operation is performed. The system supports command revocation.

15. Interpreter mode

I have a “bubble MM true classics”, there are all kinds of bubble MM’s strategy above, for example, the steps to eat western food, to see the method of the movie and so on, with MM date, as long as do a Interpreter, according to the above script implementation is ok.

Interpreter pattern: Given a language, the interpreter pattern defines a representation of its grammar and provides an interpreter at the same time. The client can use this interpreter to interpret sentences in the language. The interpreter pattern describes how to interpret these statements using the pattern design once you have a simple grammar.

The language mentioned in the interpreter schema refers to any combination that any interpreter object can interpret. In the interpreter pattern, you need to define a hierarchy of command classes that represent grammars, that is, a set of composition rules. Each command object has an interpretation method that represents the interpretation of the command object. Any permutation and combination of objects in the hierarchy of command objects is a language.

16. Iterative mode

I fell in love with Mary and threw everything out to ask her to marry me. Mary: “I have my eye on that one-carat diamond.” I: “I’ll take it. I’ll take it. Mary: “I have my eye on that villa by the lake.” ME: “I’ll take it. I’ll take it. Mary: “I like that Ferrari sports car.” MY head buzz a sound, sitting on the chair, a clench of teeth: “I buy, I buy, there is?”

Iterative mode: Iterative mode allows sequential access to elements in an aggregation without exposing the inner representation of the aggregation. The aggregate of multiple objects is called an aggregate. An aggregate object is a container object that can contain a group of objects. The iteration subpattern encapsulates the iteration logic in a separate child object, separated from the aggregation itself.

Iterative mode simplifies the aggregation interface. Each aggregation object can have one or more iteration children, and the iteration state of each iteration child can be independent of each other. Iterative algorithms can be independent of aggregation role changes.

17. The Mediator model

Four MM play mahjong, between each other who should give who how much money to calculate not clear, thanks to me at that time on the side, according to their chip number calculate money, earned money from me here, compensate for the money also pay me, everything OK, the an got four MM phone. The Mediator pattern: The mediator pattern wraps up a set of ways in which objects interact so that they don’t have to obviously interact with each other. So that they can be loosely coupled.

Changes in the roles of some objects do not immediately affect the roles of other objects. Ensure that these functions can vary independently of each other. The mediator pattern transforms many-to-many interactions into one-to-many interactions. The mediator pattern abstracts the behavior and collaboration of objects and treats the interaction of objects at small scales separately from other objects.

18. Memo mode

At the same time with a few MM chat, must remember clearly just with MM said what words, otherwise MM found will not be happy of oh, fortunately I have a memo, just with which MM said what words I have a copy of the memo inside save, so you can look at the previous record.

Memo mode: A memo object is an object that stores a snapshot of the internal state of another object. The intent of the memo pattern is to capture, externalize, and store the state of an object without breaking encapsulation, so that the object can be restored to its stored state at a later time.

19. Observer mode

Want to know our company’s latest MM intelligence? Just join the company’s MM intelligence email group. Tom is responsible for collecting intelligence, and the new intelligence he finds is directly released to the email group without informing us one by one, so that we, as subscribers (observers), can receive information in time.

Observer pattern: The observer pattern defines a multi-group dependency that allows multiple observer objects to listen on a subject object at the same time. When the topic object changes in state, all observer objects are notified so that they can update themselves automatically.

20. State mode

With the MM, must pay attention to her state oh, in different states when her behavior will be different, for example, you ask her to go to the movies tonight, the MM is not interested in you will say “there is something”, to you do not hate but not like the MM will say “ok, but can you bring my colleagues?” , already like your MM will say “what time? How about going clubbing after the movie?” Of course, you can also change the MM’s state from never hate to dislike to like.

State mode: The state mode allows an object to change its behavior when its internal state changes. The object looks as if it has changed its class. The state pattern wraps the behavior of the studied object in different state objects, each of which belongs to a subclass of an abstract state class.

The intent of the state pattern is for an object to change its behavior when its internal state changes. The state pattern requires the creation of a state class subclass for each state that the system can achieve. When the state of the system changes, the system changes the selected subclass.

21. Strategy mode

With different types of MM dating, to use different strategies, some to invite the movie is better, some to eat snacks effect is good, and some to the beach romance is the most appropriate, single purpose is to get the heart of MM, I have a lot of strategies for chasing MM. Policy pattern: The policy pattern takes a set of algorithms and encapsulates each algorithm into a separate class with a common interface, making them interchangeable.

The policy pattern allows the algorithm to change without affecting the client. The strategy module separates the behavior from the environment. The environment class is responsible for maintaining and querying the behavior class, and the various algorithms are provided in the specific policy class. Since the algorithm and the environment are independent, the increase, decrease and modification of the algorithm do not affect the environment and the client.

22. Template method pattern

Have you seen the classic article how to Convince a Girl to have Sex? There are eight Template methods for girls to get laid: bumping into each other, breaking the ice, chasing after each other, kissing, foreplay, getting your hands on each other, fondling, and getting in. But each of these steps can be done differently for different situations, and it’s up to you to improvise.

Template method pattern: The template method pattern prepares an abstract class that implements some of the logic as concrete methods and concrete constructor children, and then declares some abstract methods that force the subclasses to implement the rest of the logic. Different subclasses can implement these abstract methods in different ways, resulting in different implementations of the remaining logic. Start with a top-level logical framework and leave the details of the logic to specific subclasses.

23. Visitor pattern

The valentine day to, to give each MM send a bouquet of flowers and a card, but each MM to send flowers to her personal characteristics, each card also to choose according to individual characteristics, which make it clear, I a person or to find florists and gift shop boss to do a Visitor, let the flower shop owner according to the characteristics of the MM choose a bunch of flowers, Let the gift shop owner also choose a card for each person, so much easier;

Visitor pattern: The purpose of the visitor pattern is to encapsulate operations that are imposed on elements of a data structure. If the operation needs to be modified, the data structure that receives the operation can remain unchanged. The visitor pattern is suitable for the system where the data structure is relatively undetermined. It releases the coupling between the data structure and the operations acting on the structure, so that the operation set can be relatively free to evolve. The visitor pattern makes it easy to add new operations by adding a new visitor class. Full edition 267 pages of real case study notes on design patterns

The visitor pattern centralizes the related behavior into a visitor object rather than spreading it out into node classes. When using the Visitor pattern, put as much of the object browsing logic as possible in the visitor class rather than its subclasses. The visitor pattern can access member classes belonging to different hierarchies across several classes.