Design patterns

1. Divide by purpose

Patterns can be divided into creation patterns, structural patterns and behavioral patterns according to what they are used to accomplish.

  1. The creation pattern describes how objects are created. Its main feature is the separation of object creation and use. GoF provides five creation patterns: singleton, prototype, factory method, Abstract factory, and Builder.
  2. Structural patterns: Used to describe how classes or objects are arranged into a larger structure. GoF provides seven structural patterns: proxy, adapter, bridge, decoration, facade, share, and composition.
  3. Behavioral patterns: Describe how classes or objects work together to accomplish tasks that a single object could not accomplish alone, and how responsibilities are assigned. GoF provides 11 behavioral patterns, including template methods, policies, commands, chains of responsibility, states, observers, mediators, iterators, visitors, memos, and interpreters.

2. Divide according to scope of action

Patterns can be divided into class patterns and object patterns according to whether they are mainly used on classes or objects.

  1. Class pattern: Used to deal with relationships between classes and subclasses, which are established by inheritance and are static and determined at compile time. Factory methods, (class) adapters, template methods, and interpreters in GoF belong to this pattern.
  2. Object pattern: Used to deal with relationships between objects, which can be implemented through composition or aggregation, that can change at run time and be more dynamic. All but four of the above are object modes in GoF.

3. Function of design patterns

  • 1, FACTORY FACTORY method: chasing MM, please eat, McDonald’s wings and KFC 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 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, also can easily deal with foreign MM, This is my “I Love You” Builder. (This is definitely better than the translation machines used by the US army in Iraq.) Construction mode: The internal representation of a product is separated from the production process so that a construction process produces 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, FACTORY METHOD abstract FACTORY: 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, PROTOTYPE mode: chat with MM QQ, must say some affectionate words, I collected a lot of disgusting love words, as long as the need to copy out of the QQ inside on the line, this is my PROTOTYPE love words. Primitive model: Specify the type of object you want to create by giving a prototype object, and then create more objects of the same type by copying that 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.
  • I have six beautiful wives, all of whom are married to me. I am our Sigleton. Whenever they say “husband,” they all mean the same person, me. The singleton pattern ensures that there is only one instance of a class, and that 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.” [B: 9CECA65206] Structural model [/ B: 9CECA65206]
  • ADAPTER mode: I met a beautiful Sarah from Hong Kong at a 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 Sarah and I can talk to each other (I don’t know if he will play me) Transform the interface of one class into another that the client expects so that two classes that would otherwise not work together because of interface mismatches can work together. The adaptation class can return an appropriate instance to the client based on the parameters.
  • 7, BRIDGE mode: meet MM in the morning, say good morning, 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 to say “this morning when I met the woman with a new hairstyle”, you can use the combination of BRIDGE. Decoupling the abstraction and realization so that the two can change independently, that is, the strong association between them becomes weak association, that is, the use of composition/aggregation relationship rather than inheritance relationship between the abstraction and realization of a software system, so that the two can change independently.
  • 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, DECORATOR: 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 of some basic functions.
  • I have a professional Nikon camera, I like to manually adjust the aperture and shutter, so that the photos can be professional, but the MM does not understand these, taught for a long time will not. 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, FLYWEIGHT enjoy yuan mode: every day with MM text messages, fingers are tired to death, recently bought a new mobile phone, you can put some commonly used sentences exist in the mobile phone, when to use, directly out, in front of the name of the MM can be sent, no longer need a word a word. 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: when chatting with MM online, always start with “hi, hello”, “where are you 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.
  • RESPONSIBLEITY mode: at night when I go to English class, in order to sneak away, I take the RESPONSIBLEITY at the last row, wow, there are several beautiful MMS in front OF me, I should take a piece OF paper and write “Hi, can you be 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.
  • I have a MM home tube is particularly strict, can not meet, had to use her brother in the transmission of information between us, she has any instructions to me, write a note for her brother to 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, I have a “bubble MM True Classic”, it has all kinds of bubble MM guide, such as the steps to eat western food, to see a movie, etc., when dating with MM, just do a INTERPRETER, according to the above script. 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.
  • I fell in love with Mary and went out of my way 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?” … Iterating subpatterns: Iterating subpatterns allow 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. The iterative subpattern 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, MEDIATOR mode: four MM play mahjong, between each other who should give who how much money is not clear, fortunately at that time I was next to, according to their chips count money, earned money from me here, lost money also pay me, everything is OK, I 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, MEMENTO 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 oh, fortunately I have a memo, just with which MM said what WORDS I have a copy of the memo stored inside, so that you can always look at the previous records. 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.
  • A: Would you like to know the latest information about our company? Join the company’s MM intelligence email group. Tom is in charge of collecting intelligence, and the new information he finds is directly published to the email group without informing us one by one, so that we, as subscribers (observers), can receive information in time. The observer pattern defines a one-to-one 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 of the STATE pattern: association with MM, oh, it is important to note that her STATE in different STATE of her behavior will have different, for example, if you ask her to go to the movies tonight, not interested in you of the MM will say “something”, for you don’t hate but you don’t like the MM will say “yes, but you can take 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 STRATEGY mode: with different types of MM dating, to use different strategies, some please the movie is better, some go to eat snacks effect is good, and some go to the beach romantic the most appropriate, single purpose is to get the heart of the MM, I have a lot of STRATEGY in the MM bag. 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.
  • Have you read 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 VISITOR mode: 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. 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.