Design Patterns (32 design Patterns in Java)

Source: Internet
Author: User

turn from: leshuihttp: // blog.csdn.net/leshui/article/details/11951

In the Java version saw this article, the author of the easy language analogy Java 32 models, has a very good inspiration, but unfortunately did not give specific meaning, I added: These are the simplest introduction, to learn the words suggest you look at the "Java and Mode" this book.

Create pattern

1,factory-chase mm without eating, McDonald's chicken wings and KFC chicken wings are all mm love to eat things, although the taste is different, but no matter you take mm to McDonald's or KFC, just to the waiter said "to four chicken wings" on the line. McDonald's and KFC are the factory to produce chicken wings.

Factory mode: Separate the customer class from the factory class. Consumers need a product at any time, just request it from the factory. Consumers can accept new products without modification. The disadvantage is that when the product is modified, the factory class should also make corresponding changes. such as: How to create and how to provide to the client.

2,builder-mm most love to listen to is "I love you" this sentence, see different places of MM, to be able to use their dialect with her to say this sentence oh, I have a multi-lingual translation machine, the above each language has a button, see mm I just press the corresponding key, it can speak the corresponding language " I love you "this sentence, foreign mm can easily be fixed, this is my" I love You "builder. (This must be better sold than the American translation machine used in Iraq)

Construction mode: Separates the internal appearance of the product from the production process, thus enabling a construction process to produce a product object with different internal representations. The construction mode allows the internal representation of the product to change independently, and the customer does not need to know the details of the product internals. The construction model can enforce a step-by-stage construction process.

3,FACTORY method-please mm to McDonald's to eat hamburgers, different mm have different tastes, to each remember is a annoying thing, I generally use the FACTORY method mode, with mm to the waiter there, said "to a hamburger", specifically what kind of hamburger? Let mm directly with the waiter said on the line.

Factory method Mode: The Core factory class is no longer responsible for the creation of all products, but rather the creation of the work to the subclass to do, as an abstract factory role, is only responsible for the specific factory class must be implemented interface, and do not touch which product class should be instantiated this detail.

4,prototype-and mm with QQ chat, must say some affectionate words, I collected a lot of sweet love, need as long as copy out QQ inside on the line, this is my love PROTOTYPE. (100 bucks a share, do you want it)

Original model mode: By giving a prototype object to indicate the type of object to be created, and then creating more objects of the same type with the method of copying the prototype object. The original model mode allows the product class to be dynamically increased or decreased, and the product class does not need to have any predetermined hierarchy structure, and the original model pattern applies to any hierarchy structure. The disadvantage is that each class must be equipped with a clone method.

5,singleton-I have 6 beautiful wives, their husbands are me, I am our home husband Sigleton, they just say "husband", all refers to the same person, that is I (just had a dream, which has such a good thing)

Singleton mode: A singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance singleton pattern to the entire system. Singleton mode should only be used when there is a real "single instance" requirement.

Structural mode

6,adapter-met a beautiful woman at a friend's party, Sarah, from Hong Kong, but I will not speak Cantonese, she will not speak Putonghua, had to resort to my friend Kent, he as my and Sarah's ADAPTER, let me and Sarah can talk to each other ( I don't know if he will play me.

Adapter (transformer) mode: The interface of a class is transformed into another interface that the client expects, so that two classes that are not able to work together because of an interface cause mismatch can work together. The adaptation class can return an appropriate instance to the client based on the parameters.

7,bridge-in the morning to meet mm, to say good morning, at night met mm, to say good evening, met mm wearing a new dress, to say that your clothes are very beautiful oh, met mm new hair, to say that your hair is very beautiful oh. Do not ask me "in the morning met mm new do a hairstyle how to say" This problem, their own use of bridge combination is not on the line

Bridge mode: The abstraction and implementation of decoupling, so that they can be independent changes, that is, the strong association between them into a weak association, that is, the abstraction and implementation of a software system between the use of combination /aggregation relationship rather than inheritance, so that the two can be independent changes.

8,Composite-mary today's birthday. "My birthday, you want to give me a gift." "Well, well, go to the store and pick your own." "This t-shirt is pretty, buy, this skirt looks good, buy, this bag is also good, buy." "Hello, bought three pieces, I only promised to send a gift of OH." "What Ah, t-shirt plus skirt plus bag, just match into a set, miss, trouble you wrap up." "" ... ", MM will use composite mode, you will not?

Compositing mode: The composition mode organizes objects into a tree structure that can be used to describe the relationship between the whole and the part. A compositing pattern is a pattern that handles the tree structure of an object. The composition mode represents the relationship of the part and the whole with the tree structure. The compositing mode allows the client to treat a single constituent object in the same way as a composite object made up of them.

9,Decorator-mary after the turn to sarly birthday, or do not call her own pick, or this month food is sure to finish, take out my last year in China on the top of the photo, write on the back "the best gift, is Love your Fita", And then to the street gift shop to buy a box (selling gifts mm is also very beautiful OH), and then find the next door to make art design Mike designed a beautiful box installed up ..., we are all decorator, and finally all in the decoration of my this person ah, how, understand?

Decorative mode: The ability to extend objects transparently to clients is an alternative to inheritance, providing more flexibility than inheritance. Dynamically adds functionality to an object that can be undone on the fly. Adds a very large amount of functionality resulting from the combination of some basic functions.

10, facade-I have a professional Nikon camera, I like to manually adjust the aperture, shutter, so that the photo is professional, but mm can not understand these, taught a half day will not. Fortunately, the camera has facade design mode, the camera to adjust the automatic file, as long as the target to press the shutter line, everything from the camera automatically adjust, so mm can also use this camera to take a picture of me.

Façade mode: External communication with a subsystem must be done through a unified façade object. Façade mode provides a high-level interface that makes subsystems easier to use. Each subsystem has only one façade class, and this façade class has only one instance, meaning it is a singleton pattern. But the entire system can have multiple façade classes.

11, flyweight-every day with the mm text messages, fingers are exhausted, recently bought a novice machine, you can put some commonly used sentences exist in the cell phone, to use the time, directly out, in front with the name of the MM can be sent, and do not use a word a word knocked. The shared sentence is that the flyweight,mm name is the extracted external feature, which is used according to the context.

Enjoy meta-mode: Flyweight is the most lightweight in a boxing match. The enjoy meta-mode efficiently supports a large number of fine-grained objects in a shared manner. The key to sharing the shared meta-mode is to differentiate between intrinsic state and external state. The intrinsic state is stored inside the element, and does not vary with the environment. The state of the outer Yun is changed with the change of the environment. The outer state can not affect the intrinsic state, they are independent of each other. Separates the states that can be shared and the states that cannot be shared from the regular class, removing the state that cannot be shared from the class. Instead of creating the shared object directly, the client should use a factory object responsible for creating the object being shared. The enjoy meta-mode significantly reduces the number of objects in memory.

12, proxy-and MM in the online chat, a beginning always "Hi, hello", "Where do you come from?" "How old are you?" "How tall?" "These words, really annoying, write a program as my proxy bar, usually received these words are set up the automatic answer, received other words when I told me to answer, how, cool."

Proxy mode: The proxy mode provides a proxy object for an object, and the proxy object controls the reference to the source object. An agent is a person or an institution acting on behalf of another person or an institution. In some cases, the client does not want or cannot refer directly to an object, and the proxy object can act as an intermediary directly between the customer and the target object. The client cannot distinguish between a proxy subject object and a real subject object. Proxy mode can not know the real proxy object, but only hold a proxy object interface, this time the proxy object can not create the proxy object, the proxy object must have the other role of the system to create and pass in.

Behavioral patterns

13, CHAIN of responsibleity-evening to the English class, in order to good to go to the last row, wow, sitting in front of several beautiful mm hey, find a note, write "Hi, can do my girlfriend?" If you do not want to pass forward ", the note on one after another to pass up, bad, to the first row of MM to pass the note to the teacher, I heard it is an old maid, run!

Responsibility chain mode: In the responsibility chain model, many objects are connected by each object's reference to its next

Up to form a chain. The request is passed on this chain until an object on the chain decides to process the request. The customer does not know which object on the chain is ultimately processing the request, and the system can dynamically reorganize the chain and assign responsibility without affecting the client. The processor has two choices: take responsibility or push the responsibility to the other person. A request can eventually not be accepted by any receive-side object.

14, command-I have a mm home tube special strict, can not meet, had to rely on her brother in between us to send information, she told me what instructions, write a note let her brother brought to me. This is not, her brother sent over a command, in order to thank him, I asked him to eat a bowl of mixed sauce noodles, how he said: "I also give my sister three boyfriend sent command, count you the most stingy, just ask me to eat noodles." ”,:-(

Command mode: The command mode encapsulates a request or action into an object. The command mode divides the responsibility for issuing the command and the responsibility for executing the command, delegating it to different objects. The command pattern allows the requesting party to be independent of the sending party, so that the requesting party does not have to know the interface of the party receiving the request, not to know how the request was received, and whether the operation was executed, when it was executed, and how it was executed. The system supports undo of the command.

15, interpreter-I have a "bubble mm canon", there are various bubble mm, such as the steps to eat Western food, to see the method of the film and so on, with the MM date, as long as a interpreter, according to the above script execution on it.

Interpreter mode: Given a language, the interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. The client can use this interpreter to interpret the sentences in the language. The interpreter pattern describes how to interpret these statements using a pattern design after having a simple grammar. The language mentioned in the interpreter pattern 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, which is a series of composition rules. Each command object has an explanatory method that represents the interpretation of the Command object. Any permutation combination of objects in the hierarchy of command objects is a language.

16. iterator-I fell in love with Mary and was desperate to marry her.

Mary: "If you want me to marry you, I have to promise my terms."

Me: "What are the terms I promise, you say?"

Mary: "I have a crush on that one-carat diamond."

Me: "I buy, I buy, still have?" ”

Mary: "I have a crush on the villa by the lake."

Me: "I buy, I buy, still have?" ”

Mary: "Your penis has to be 50cm long."

My head is humming, sitting in a chair, a bite: "I cut, I cut, and there?" ”

...

Iterative sub-patterns: Iterative sub-patterns can sequentially access an element in a cluster without exposing the aggregated interior representation. Aggregates are collectively called aggregates, and clustered objects are container objects that can contain a set of objects. The iterative sub-pattern encapsulates the iterative logic into a separate sub-object, which is separated from the aggregation itself. Iterative sub-patterns simplify the aggregation of the interface. Each clustered object can have one or more iteration sub-objects, and the iteration state of each iteration can be independent of each other. Iterative algorithms can be independent of aggregate role changes.

17, mediator-four mm playing mahjong, between each other who should give who how much money is not clear, fortunately at that time I was in the side, according to the respective chips count money, earn money from me here, lost the money also pay me, all OK, I got four mm phone.

Mediator mode: The Mediator pattern wraps a series of objects interacting in such a way that the objects do not have to interact with each other clearly. So that they can be loosely coupled. When the role of some objects changes, it does not immediately affect the effect of other objects. Ensure that these effects can change independently of each other. The mediator model converts many-to-many interactions into one-to-many interactions. The Mediator pattern abstracts the behavior and collaboration of objects, and separates them from the interactions of other objects on small-scale behaviors.

18, memento-at the same time with a few mm chat, be sure to remember what you said with mm what words, otherwise mm found will not happy oh, fortunately I have a memo, just with which mm said what words I have to copy a copy put to memo inside save, so can look at the previous record.

Memo Mode: A Memo object is an object used to store a snapshot of the internal state of another object. The purpose of the memo mode is to capture the state of an object without destroying the package, and to externally and store it so that it can be restored to the stored state at the appropriate time in the future.

19, observer-want to know our latest mm information? Join the company's MM intelligence mail group on the line, Tom is responsible for collecting intelligence, he found that the new information without a notice to us, directly to the Mail group, we as subscribers (observers) can receive information in a timely manner

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

20. state-with MM, must pay attention to her state, oh, in different states, her behavior will be different, such as you ask her to go to the movies tonight, you are not interested in mm will say "There is something," You do not hate but still do not like the MM will say "good ah, but can bring my colleague?" "What time is it that you've already liked your mm?" Why don't you go clubbing after the movie? "Of course, you see the film in the process of good performance, you can also put the status of MM never hate to become like oh."

State mode: state mode allows an object to change behavior when its internal state changes. This object looks like it has changed its class. State mode wraps the behavior of the object being studied in a different state object, and each state object belongs to a subclass of an abstract state class. The intent of the state pattern is to change the behavior of an object as it changes its internal state. State mode requires the creation of a subclass of a State class for each of the possible states of a system. When the state of the system changes, the system changes the selected subclass.

21, strategy-with different types of mm dating, to use a different strategy, some of the film is better, some go to eat snack effect is good, some to the seaside romantic most suitable, single purpose is to get mm heart, I chase mm Jin sac has a lot of strategy oh.

Policy mode: The policy mode is for a set of algorithms that encapsulate each algorithm in a separate class with a common interface so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. The strategy model separates behavior from the environment. The Environment class is responsible for maintaining and querying behavior classes, and various algorithms are available in specific policy classes. Because the algorithm and the environment independent, the algorithm increases or decreases, the modification will not affect the environment and the client.

22, TEMPLATE method--read "How to persuade girls to bed" This classic article? Girls from the realization of the same steps to go to bed, break the deadlock, pursue, kiss, foreplay, hands, Caress, go into eight steps (Template method), but each step for different situations, there is not the same approach, it depends on you improvise (concrete implementation);

Template method Pattern: Template method Schema prepares an abstract class, implements partial 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, thus having different implementations of the remaining logic. First, a top-level logical framework is developed, and the details of the logic are left to the specific subclasses to implement.

23, visitor-Valentine's Day to, to give each mm send a bouquet of flowers and a card, but each mm sent to the flowers to her personal characteristics, each card also according to the characteristics of individual to pick, I am a person who make clear, or find florist shop owner and gift shop boss do a VISITOR, Let flower shop owner according to the characteristics of mm choose a bouquet of flowers, so that the gift shop owner also choose a card according to the characteristics of each person, so much easier;

Visitor pattern: The purpose of the visitor pattern is to encapsulate some action that is applied to a data structure element. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged. The visitor pattern is suitable for systems with relatively indeterminate data structures, which frees up the coupling between the structure and the operation of the structure so that the set of operations can evolve relatively freely. The visitor pattern makes it easy to add new operations, which is to add a new visitor class. The visitor pattern concentrates the behavior on a visitor object, rather than spreading it across a node class. When you use the visitor pattern, you put as much of the object-browsing logic in the visitor class as possible, rather than in its subclasses. The visitor pattern can access member classes belonging to different hierarchical structures across hierarchical structures of several classes.

Design Patterns (32 design Patterns in Java)

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.