1. Creation Design Pattern
1. FACTORY—If you want to chase a girl, you must treat her to a meal. McDonald’s chicken wings and KFC chicken wings are both things that girls love to eat. Although the tastes are different, no matter you If you take your girl to McDonald's or KFC, just ask the waiter, "Four chicken wings." McDonald's and KFC are Factory
that produce chicken wings. Factory model: customer class and factory class are separated. Anytime a consumer needs a certain product, they just need to request it from the factory. Consumers can accept new products without modification. The disadvantage is that when the product is modified, the factory class must also be modified accordingly. Such as: how to create and how to provide it to the client.
2. BUILDER—What girls love to hear the most is "I love you". When meeting girls from different places, you should be able to say this to them in their dialect. I have a multilingual background. The translator has a button for each language. When I see a girl, I just need to press the corresponding button, and it will be able to say "I love you" in the corresponding language. Foreign girls can also easily do it. This is my "I love you" builder. (This must be easier to sell than the translator used by the US military in Iraq)
Construction mode: Separate the internal representation of the product from the product generation process, so that one construction process generates product objects with different internal representations. The construction mode allows the internal appearance of the product to be changed independently, and the customer does not need to know the details of the internal composition of the product. Build mode enforces a step-by-step building process.
3. FACTORY METHOD—Invite MM to McDonald’s to eat hamburgers. Different MMs have different tastes. It’s annoying to remember each one. I usually use the Factory Method mode and take MM to the waiter. When you say "I want a burger", just ask the girl to tell the waiter directly what kind of burger you want.
Factory method pattern: The core factory class is no longer responsible for the creation of all products, but leaves the specific creation work to subclasses, becoming an abstract factory role, only responsible for providing the interfaces that specific factory classes must implement. Without touching the details of which product class should be instantiated.
4. PROTOTYPE—When chatting with a girl on QQ, you must say some affectionate words. I have collected a lot of disgusting love words. If necessary, just copy them and put them in QQ. This is my prototype of love words. (100 yuan a copy, do you want it)
Original model mode: 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 the dynamic addition or reduction of product categories. The product categories do not need to have any predetermined hierarchical structure. The original model pattern is suitable for any hierarchical structure. The disadvantage is that every class must be equipped with a clone method.
5. SINGLETON—I have 6 beautiful wives. Their husbands are all me. I am the husband Sigleton in our family. As long as they say "husband", they all refer to the same person, that is me (just did It’s a dream, how can such a good thing happen)
Singleton mode: Singleton mode ensures that there is only one instance of a certain class, and it instantiates itself and provides these
instances to the entire system. Singleton mode. The singleton pattern should only be used when there is a true "single instance" requirement.
2, Structural Model
6. ADAPTER—I met a beautiful woman named Sarah at a friend’s party. She came from Hong Kong, but I can’t speak Cantonese and she can’t speak Mandarin, so I had to turn to my friend kent for help. Now, he serves as the Adapter between Sarah and I, allowing Sarah and I to talk to each other (I don’t know if he will play tricks on me)
Adapter (transformer) mode: Transform the interface of a class into what the client Another interface to look forward to, so that two classes that originally could not work together due to mismatched interfaces can work together. The adaptation class can return a suitable instance to the client based on the parameters.
7. BRIDGE—When you meet a girl in the morning, say good morning; when you meet a girl at night, say good evening; when you meet a girl wearing a new dress, say your dress is so beautiful. When you meet a girl, you have to say good evening. Your hair is so beautiful. Don't ask me questions like "What do you say when you meet your girlfriend with a new hairstyle this morning?", just use BRIDGE to combine it yourself
Bridge pattern: Decouple abstraction from implementation so that the two can change independently , that is to say, changing the strong association between them into a weak association, which means using a combination/aggregation relationship instead of an inheritance relationship between the abstraction and implementation of a software system, so that the two can change independently.
8. COMPOSITE—Mary’s birthday is today. "It's my birthday, and you want to give me a gift." "Well, okay, go to the store and choose it yourself." "This T-shirt is pretty, buy it, and this skirt is pretty, buy it, and this bag is pretty good, too. Buy it." "Hey, I bought three pieces. I only promised to give you one gift." "What, a T-shirt, a skirt and a bag make a perfect set. Miss, please wrap it up. ""...", MM will use Composite mode, have you mastered it?
Composite mode: Composite mode organizes objects into a tree structure and can be used to describe the relationship between the whole and its parts. The composition pattern is a pattern that deals with tree structures of objects. The synthesis mode represents the relationship between the part and the whole using a tree structure. The composition mode allows the client to treat individual component objects equally as the composite object composed of them.
9. DECORATOR—After Mary celebrates, it’s Sarly’s turn to celebrate her birthday. It’s better not to ask her to choose by herself, otherwise the food expenses for this month will definitely be spent. Take out the photo I took on the top of Huashan Mountain last year and write " The best gift is to love you Fita." I went to the gift shop on the street and bought a photo frame (the girl who sells gifts is also very beautiful), and then asked Mike, who is an art designer next door, to design a beautiful box to put it in. „„We are all Decorators, and ultimately we are decorating me as a person. How about it? Do you understand?
Decoration mode: Decoration mode extends the functionality of objects in a transparent way to the client. It is an alternative to inheritance and provides more flexibility than inheritance. Dynamically add functions to an object, and these functions can be dynamically undone. Adding a very large amount of functionality resulting from permutations and combinations of some basic functionality.
10. FACADE—I have a professional Nikon camera, and I like to manually adjust the aperture and shutter by myself, so that the photos taken will be professional, but MM doesn’t understand this, and she can’t even teach it for a long time. Fortunately, the camera has a Facade design mode. If you adjust the camera to automatic mode, you just need to aim at the target and press the shutter button. Everything will be automatically adjusted by the camera, so MM can also use this camera to take pictures of me.
Facade mode: External communication with a subsystem must be carried out through a unified facade object. The Facade pattern 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, which means it is a singleton pattern. But the entire system can have multiple facade classes.
11. FLYWEIGHT—Sending text messages to MM every day makes my fingers exhausted. I recently bought a new mobile phone. I can store some commonly used sentences in the phone. When I need to use it, I can just take it out and add MM in front of it. Your name can be sent without typing it word by word. The shared sentence is Flyweight, and the name of MM is the extracted external feature, which is used according to the context.
Flyweight mode: FLYWEIGHT refers to the bantamweight in boxing matches. Flyweight mode efficiently supports a large number of fine-grained objects in a shared manner. The key to sharing the flyweight model is to distinguish between intrinsic and extrinsic states. The intrinsic state is stored inside the flyweight and will not change with changes in the environment. The external state changes with changes in the environment. Extrinsic states cannot affect intrinsic states, they are independent of each other. Distinguish the state that can be shared from the state that cannot be shared from regular classes, and remove the state that cannot be shared from the class. The client cannot directly create shared objects, but should use a factory object to create shared objects. Flyweight mode greatly reduces the number of objects in memory.
12. PROXY - When chatting with a girl online, it always starts with "Hi, hello", "Where are you from?" "How old are you?" "How tall are you?" These words are really annoying. Write a program. How about it be my Proxy, and set up an automatic answer when receiving these words, and then notify me of the answer when receiving other words, how about that, cool.
Proxy mode: Proxy mode provides a proxy object for a certain object, and the proxy object controls the reference to the source object. Agency is when a person or institution acts on behalf of another person or institution. In some cases, the client does not want or cannot directly reference an object, and the proxy object can directly act as an intermediary between the client and the target object. The client cannot tell the difference between a proxy topic object and a 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 create the proxy object. The proxy object must be created and passed in by other roles in the system.
三, Behavior Pattern
13. CHAIN OF RESPONSIBLEITY—I went to English class in the evening, and I sat in the last row just to be comfortable. Wow, there were several beautiful girls sitting in front of me. Find a note and write "Hi, can you be my girlfriend? If you don't want to, please pass it forward." The notes were passed up one after another. Oops, the girl in the first row passed the note to the teacher. I heard She's an old maid, run!
Chain of responsibility model: In the chain of responsibility model, many objects are connected by each object's reference to its next home to form a chain. The request is passed up the chain until an object in the chain decides to handle the request. The client does not know which object in the chain ultimately handles the request, and the system can dynamically reorganize the chain and assign responsibilities without affecting the client. The processor has two choices: accept responsibility or pass it on to the next party. A request can ultimately not be accepted by any receiving object.
14. COMMAND—I have a girl whose family is very strict and we can’t meet each other, so she has to rely on her brother to send messages between us. If she has any instructions for me, just write a note to her brother. bring me. No, her brother sent another COMMAND. In order to thank him, I treated him to a bowl of miscellaneous noodles. Unexpectedly, he said: "I sent COMMANDs to my sister's
three boyfriends at the same time, and you are the youngest. You are so angry that you invited me to eat noodles.",
Command mode: The command mode encapsulates a request or operation into an object. The command pattern separates the responsibility for issuing commands and the responsibility for executing commands, and delegates them to different objects. The command mode allows the requesting party to be independent from the sending party, so that the requesting party does not need to know the interface of the party receiving the request, let alone how the request is received, and whether, when and how the operation is executed. of. The system supports the undo of commands.
15. INTERPRETER—I have a "True Book of Picking Up Girls", which contains various strategies for picking up girls, such as the steps to eat Western food, how to go to the movies, etc. When dating a girl, you only need to do one Interpreter, just follow the above script and execute it.
Interpreter mode: Given a language, the interpreter mode can define a representation of its grammar and provide an interpreter at the same time. Clients can use this interpreter to interpret sentences in this language. The Interpreter pattern describes how to interpret these statements using a pattern design, given a simple grammar. The language mentioned in the interpreter pattern refers to any combination that any interpreter object can interpret. In the interpreter mode, it is necessary to define a hierarchical structure of command classes that represent grammar, that is, a series of combination rules. Each command object has an interpretation method, which represents the interpretation of the command object. Any permutation and combination of objects in a hierarchy of command objects is a language.
16. ITERATOR—I fell in love with Mary and proposed to her desperately.
Mary: "If you want me to marry you, you have to agree to my conditions."
Me: "I'll agree to any conditions, just tell me."
Mary: "I'm attracted to that one-carat diamond. ”
Me: “I buy it, I buy it, is there any more?”
Mary: “I’m interested in the villa by the lake”
Me: “I buy it, I buy it, is there any more?” ?”
Mary: “I’m attracted to that Ferrari sports car”
My head buzzed, I sat on the chair and gritted my teeth: “I’ll buy it, I’ll buy it, is there any more?”
„„
Iterative subpattern: The iterative subpattern allows sequential access to the elements in a collection without exposing the internal representation of the collection. The aggregate formed by multiple objects coming together is called an aggregation. An aggregation object is a container object that can contain a group of objects. The iteration subpattern encapsulates the iteration logic into a separate sub-object, separate from the collection itself. The iterative subpattern simplifies the interface for aggregation. Each aggregate object can have one or more iterator sub-objects, and the iteration status of each iterator can be independent of each other. The iterative algorithm can vary independently of the aggregation role.
17. MEDIATOR—Four girls were playing mahjong, and they couldn’t figure out how much money they should give to each other. Fortunately, I was around at the time and calculated the money according to their respective chip numbers. Those who made money took it from me. Those who lost money also paid me, and everything was OK. I got the phone numbers of four girls.
Delayer mode: The mediators packaged a series of objects to interact, so that these objects do not have to work with each other. This allows them to be loosely coupled. When the interaction between some objects changes, it will not immediately affect the interaction between other objects. Ensure that these effects can be changed independently of each other. The Mediator pattern converts many-to-many interactions into one-to-many interactions. The mediator pattern abstracts the behavior and collaboration of objects and handles the small-scale behavior of objects separately from the interactions with other objects.
18. MEMENTO—When chatting with several girls at the same time, be sure to remember clearly what you just said to the girl, otherwise the girl will be unhappy when she finds out. Fortunately, I have a memo about which girl I just talked to. I make a copy of everything I say and put it in my memo so I can check my previous records at any time.
Memo mode: Memo object is an object used to store a snapshot of the internal state of another object. The purpose of the memo pattern is to capture, externalize, and store the state of an object without destroying the encapsulation, so that the object can be restored to its stored state at an appropriate time in the future.
19. OBSERVER—Want to know the latest MM information of our company? Just join the company's MM intelligence email group. Tom is responsible for collecting intelligence. He does not need to notify us one by one of the new information he discovers. He publishes it directly to the email group. As subscribers (observers), we can receive the intelligence in time
Observer pattern: The observer pattern defines a multi-team dependency relationship, allowing multiple observer objects to monitor a certain subject object at the same time. When this topic object changes state, it notifies all observer objects, allowing them to update themselves automatically.
20. STATE—When dating a girl, you must pay attention to her state. Her behavior will be different in different states. For example, if you ask her to go to the movies tonight, a girl who is not interested in you will If you say "Something's going on", a girl who doesn't hate you but hasn't fallen in love with you yet will say "Okay, but can I bring my colleague with you?", and a girl who already likes you will say "What time is it? Look. How about going to the bar after the movie?" Of course, if you behave well while watching the movie, you can also change the girl's status from hating or disliking to liking it.
State Pattern: State pattern allows an object to change its behavior when its internal state changes. The object appears to have changed its class. The state pattern wraps the behavior of the object under study in different state objects. Each state object belongs to a subclass of an abstract state class. The intention of the state pattern is to allow an object to change its behavior when its internal state changes. The state pattern requires the creation of a subclass of the state class for each state that the system may obtain. When the state of the system changes, the system changes the selected subclass.
21, Strategy — Dating different types of MMs, you need to use different strategies, some are better to ask movies, and some are good at eating snacks. Some go to the sea romance. MM’s heart, I have a lot of strategies in my toolkit for chasing MM.
Strategy pattern: Strategy pattern targets a set of algorithms and encapsulates each algorithm into an independent class with a common interface, so that they can be replaced with each other. The strategy pattern allows the algorithm to change without affecting the client. The strategy pattern separates behavior from the environment. The environment class is responsible for maintaining and querying the behavior class, and various algorithms are provided in specific strategy classes. Since the algorithm and the environment are independent, the addition, deletion, and modification of the algorithm will not affect the environment and the client.
22. TEMPLATE METHOD——Have you read the classic article "How to Convince a Girl to Go to bed"? Girls realize that the unchanging steps of getting into bed are divided into eight steps (Template method): chance encounter, breaking the ice, pursuing, kissing, foreplay, hands-on, caressing, and entering. However, each step is different for different situations. How to do it depends on your adaptability (specific implementation);
Template method pattern: The template method pattern prepares an abstract class, implements part of the logic in the form of concrete methods and concrete constructors, and then declares some abstract methods to Force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways and thus have different implementations of the remaining logic. Develop a top-level logic framework first, and leave the details of the logic to specific subclasses.
23. VISITOR—Valentine’s Day is here, and each girl should be given a bouquet of flowers and a card. However, the flowers sent by each girl must be based on her personal characteristics, and each card should also be based on her personal characteristics. I can’t figure it out on my own, so I’d better ask the florist and the gift shop owner to be visitors. Let the florist choose a bouquet of flowers based on the girl’s characteristics, and let the gift shop owner choose a card based on each person’s characteristics. This is much easier;
Visitor pattern: The purpose of the visitor pattern is to encapsulate some operations that are applied to certain data structure elements. Once these operations need to be modified, the data structure accepting this operation can remain unchanged. The visitor pattern is suitable for systems with relatively undetermined data structures. It decouples the coupling between the data structure and the operations that act on the structure, allowing the set of operations to evolve relatively freely. The visitor pattern makes it easy to add new operations by adding a new visitor class. The visitor pattern concentrates related behaviors into a visitor object instead of dispersing them into node classes. When using the Visitor pattern, place as much object browsing logic as possible in the Visitor class rather than in its subclasses. The visitor pattern can access member classes belonging to different hierarchies across several class hierarchies.
The above is the detailed content of Dahua PHP's 23 design patterns, high energy and no peeing spots throughout the process. For more information, please follow other related articles on the PHP Chinese website!