Interesting insights about 23 design patterns in Java

Source: Internet
Author: User

Source: http://developer.51cto.com/art/201205/338617.htm

Fluent in the network of a very broad old article, temporarily did not find the original author, currently seen the earliest reprint time is February 28, 2005. Author with

The easy language, the image explains 23 kinds of patterns, has the very good inspiration function.

Create pattern

1, factory-chase mm, please eat, McDonald's chicken wings and KFC chicken wings are all mm love to eat things, although the taste has not

With, but no matter you take mm to McDonald's or KFC, just say to the waiter "Four chicken Wings" on the line. McDonald's and KFC produce chicken wings.

Factory.


Factory mode: Separate the customer class from the factory class. Consumers need a product at any time, just request it from the factory. Consumers do not need to modify it

Accept new products. 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 speak to her in their dialect 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 be said in the corresponding language

out "I Love You "this sentence, foreign mm can easily be fixed, this is my" I love You "builder. (This must be more than the American translation machine used in Iraq

Good sell)


Construction mode: Separates the internal appearance of the product from the product's generation process, thus enabling a construction process to produce products with different internal representations

Object. 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 impose a

The construction process is carried out in steps.


3, FACTORY method-please mm to McDonald's to eat hamburgers, different mm have different tastes, to each remember is a annoying thing,

Sentiment, I generally use factory method mode, with mm to the waiter there, said "want a hamburger", specifically what kind of hamburger, let mm direct

Just tell the waiter.


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 sub-class to do, to become an abstract factory

Role, it is only the responsibility to give the interface that a specific factory class must implement, without touching which product class should be instantiated in this detail.


4, prototype-and mm with QQ chat, must say some affectionate words, I collected a lot of sweet nothings, when needed as long as copy out

To put in QQ inside on the line, this is my sweet nothings 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 using the method of copying the prototype object to create a more

Multiple objects of the same type. The original model mode allows to dynamically increase or decrease the product class, the product class does not need to have any predetermined hierarchy structure, the original

Model patterns apply to any hierarchical 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 the husband of our family Sigleton, they just said "old

Public ", 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. Single-Case 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 can not speak Putonghua, had to beg

Helped my friend Kent, who, as a adapter between Sarah and me, let me and Sarah talk to each other (and I don't know if he will play with me)


Adapter (transformer) mode: The interface of a class is transformed into another interface that the client expects, so that it does not match the interface cause.

The two classes that work together can work together. The adaptation class can return an appropriate instance to the client based on the parameters.


7, bridge-morning met mm, to say good morning, at night met mm, to say good evening, met mm wearing a new dress, to say your clothes

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 hair how to say" this problem, since

You can combine it with a bridge.


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, it is

means that use a combination/aggregation relationship rather than an inheritance relationship between abstraction and implementation of a software system so that the two can change independently.


8, Composite-mary today's birthday. "My birthday, you want to give me a gift." "Well, well, go to the store, you pick yourself." "" This piece of T

The shirt is very beautiful, buy, this skirt good-looking, buy, this bag is also good, buy. "Hey, bought three pieces, I only promised to send a gift oh." "" What , T

shirt plus skirt plus bag, just match into a set yes, Miss, trouble you wrap up. "" ... ", MM will use composite mode, you will not have?


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. The compositing pattern is a tree that handles objects

The pattern of the structure. The composition mode represents the relationship of the part and the whole with the tree structure. The compositing mode allows the client to put a separate component object and by his

Synthetic objects that are compounded by the same view.


9, decorator-mary after the turn to sarly birthday, or do not call her own pick, or this month food will definitely finish, take out my

Last year's photo on the top of China, wrote on the back "the best gift, is Love your Fita", and then to the street gift shop bought a picture box (selling gifts mm

Also very beautiful), and then find the next door to make art design Mike designed a beautiful box to pack up ..., we are all decorator, and finally are decorated

I am a person, how, do you understand?


Decorative mode: The ability to extend objects transparently to the client is an alternative to inheritance, providing more spirit than inheritance

Activity. Dynamically adds functionality to an object that can be undone on the fly. Increase the number of combinations of basic functions that result in a very large amount of

Function.


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 for a long while not. Fortunately, the camera has a facade design mode, adjust the camera to the automatic file, as long as the target to press the shutter on the line, a

The camera automatically adjusts, 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. The façade mode provides a high-level interface that enables

Subsystems are 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 whole

A system can have multiple façade classes.


11, flyweight-every day with the mm texting, fingers are exhausted, recently bought a novice machine, you can put some common sentences exist mobile phone

, to use the time, directly to take out, in front of the name of the MM can be sent, do not use a word a word knocked. The shared sentence is

FLYWEIGHT,MM's 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. Enjoy RMB

The key to sharing the pattern is to differentiate between intrinsic state and outer state. The intrinsic state is stored inside the element, and does not vary with the environment. Wai Yun

The state is changed with the change of the environment. The outer state can not affect the intrinsic state, they are independent of each other. The states that will be shared and those that cannot be shared

State is distinguished from the regular class and the state that cannot be shared is removed from the class. Clients are not allowed to create shared objects directly, but should use the

A factory object is responsible for creating the objects that are 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?" ”,

it some words, really annoying, write a program as my proxy bar, usually received these words are set up the automatic answer, receive other words when the notice

I'm answer, What's up, 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 a

a machine Act 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 be

Customer and the target object directly play an intermediary role. The client cannot distinguish between a proxy subject object and a real subject object. Proxy mode can not know the real

by the Generation object, and the proxy object cannot create a proxy object, the proxy object must have a system

other The role is created and passed on behalf of.

Behavioral Patterns

13, CHAIN of responsibleity-evening to go to the English class, in order to good getaway sat to the last row, wow, sitting in front of several beautiful

MM Ah, find a note, write "Hi, can I be my girlfriend?" If you do not want to pass forward ", the note will be transmitted one by one, bad,

To the first row of MM to pass the note to the teacher, I heard that 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. Request to upload in this chain

until one of the objects on the chain decides to process the request. The customer does not know which object on the chain will handle the request at the end, and the system can not affect

dynamically reorganize chains and assign responsibilities in the case of clients. The processor has two choices: take responsibility or take responsibility to the other person. A request can be the most

is not accepted by any receiving end 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 to me

What's instructions, write a note for her brother to bring to me. This is not, her brother sent over a command, in order to thank him, I asked him to eat a bowl

Miscellaneous Sauce , 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 the issue of the command and the duty of execution.

On, delegating 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 party receiving the request

interface, 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 the withdrawal of commands

Extinction


15, interpreter-I have a "bubble mm canon", which has a variety of bubble mm strategy, such as to eat Western steps, to see the film

Method and so on, with the MM date, as long as a interpreter, follow the script above to execute it.


Interpreter mode: Given a language, the interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. Client can

Use this interpreter to explain the sentences in the language. The interpreter pattern describes how to use a pattern design to interpret these after a simple grammar

Statement. The language mentioned in the interpreter pattern refers to any combination that any interpreter object can interpret. In the interpreter mode, you need to define a representative text

The hierarchical structure of the command class of the method, which is a series of combination rules. Each command object has an explanatory method that represents the interpretation of the Command object. Life

Any permutation of objects in the hierarchy of 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. Multiple objects are gathered together to form a

Collectively called aggregation, a clustered object is a container object that can contain a set of objects. The iterative sub-pattern encapsulates the iterative logic into a separate sub-object, from

and 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, each of which

The iteration states of an 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, I was in the side, according to their own raise

Code count money, earn money from my here to take, lost money also pay me, everything 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

Loosely coupled. When the role of some objects changes, it does not immediately affect the effect of other objects. To ensure that these effects are unique to each other

Changes in the state. The mediator model converts many-to-many interactions into one-to-many interactions. The Mediator pattern abstracts the behavior and collaboration of objects,

Like interacting with other objects in small-scale behavior.


18, memento-at the same time with a few mm chat, be sure to remember what just 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 a copy of the memo to save, so you can always check the previous record

Recorded.


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 not break the seal

Conditions, the state of an object is caught, and is externally stored, so that it can be restored to storage at the appropriate time in the future

The state.


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

New information found without a notice to us, directly to the mailing 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. This theme

Object When a change occurs in the state, all observer objects are notified so that they can automatically update themselves.


20, state-and mm contact, must pay attention to her state oh, in different states, her behavior will be different, such as you ask her this evening

Go to the movies, you are not interested in mm will say "There is something," You do not hate but not like the MM will say "Yes, but you can take my colleague

Do you? "What time is it that you've already liked your mm?" Why don't you go clubbing after the movie? "And of course you do well in the process of watching movies, you can also

In order to put the status of MM never hate not like 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. State

The intent of a pattern is to change the behavior of an object as it changes its internal state. State mode requires a possible state for each system

Create a subclass of a State class. 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, there

To the seaside romantic most suitable, single purpose is to get the heart of MM, I chase mm Jin sac has a lot of strategy oh.


Policy mode: Policy mode for a set of algorithms, each algorithm is encapsulated in a separate class with a common interface, so that they can replace each other

Change. The policy pattern allows the algorithm to change without affecting the client. The strategy model separates behavior from the environment. The environmental category is responsible for maintaining and checking

The various algorithms are provided in the specific policy class. As the algorithm and the environment are independent, the increase or decrease of the algorithm will not affect the environment and the customer

End.


22, TEMPLATE method--read "How to persuade girls to bed" This classic article? Girls from the realization to go to bed with the constant steps of

In order to encounter, break the deadlock, pursue, kiss, foreplay, hands-on, caress, go into eight steps (Template method), but each step for different

Situation, there are different practices, it depends on you to improvise (concrete implementation);


Template method Pattern: Template method Schema prepares an abstract class that implements part of the logic in the form of concrete methods and concrete constructors, and then declares a

Some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different logic for the rest

The implementation. 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 give each mm send a bouquet of flowers and a card, but each mm send flowers to her personal special

Points, each card should also be based on the characteristics of the individual to pick, I am a person who can make clear, or to find the florist and gift shop owner to do a visitor, let flower shop

The boss 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 actions need to be modified,

The data structure that accepts this operation can remain unchanged. The visitor pattern is suitable for systems with relatively indeterminate data structures, which structure and function

The interaction between the operations is free, allowing the set of operations to evolve relatively freely. The visitor pattern makes it easy to add new operations, which is to increase

A new visitor class. The visitor pattern concentrates the behavior on a visitor object, rather than spreading it across a node class. When using the interview

In the reader mode, you put as much of the object navigation logic in the visitor class as possible, rather than in its subclasses. The visitor pattern can span several classes of

Hierarchical structures access member classes that belong to different hierarchy structures.



Interesting insights about 23 design patterns in Java

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.