Design Patterns in Android _android

Source: Internet
Author: User
Tags first row

Generally speaking, the following eight kinds of design patterns are commonly used: single example, factory, observer, Agent, command, adapter, synthesis, visitor

Single case mode: The goal is to have only one calling object in the system, the disadvantage of which is that it makes other programs rely too much on it, and that different single cases run in different processes, making maintenance difficult;

Factory Pattern: The production fixed some things, such as abstract class, the disadvantage is the product modification trouble; if people like action movies and love movies Send the same request to the server, they can get the set of movies they want to see, which is the same request of different objects, the requirements are met.

Observer mode: Is that multiple objects to monitor an object, such as caching;

Agent mode: Their own things to others to do, the return of the results can be, such as asynchronous thread;

Command mode: The separation between the calling object and the action object, and the middleware to coordinate the work between the two, such as the controller;

Adapter mode: Turn an interface into the interface that the user needs, such as Baseadapter to fit ListView and spinner, because they have the same interface

Synthetic mode: Converts a one-to-many relationship into a pair of whole relationships, such as ListView and adapters;

Visitor pattern: Different processing for different objects, such as instanceof.

There is a friend on the internet to explain the design pattern is very interesting, excerpts to the following, but can not find the original author, so did not add the original address also please forgive me ha!

Create pattern

1, factory-chase mm can not eat, McDonald's chicken wings and KFC's 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 to the waiter said "to four chicken wings" on the line. McDonald's and KFC are the factory for making chicken wings.

Factory mode: Customer class and factory class separate. Any time a consumer needs a product, just ask the factory. Consumers can accept new products without modification. The disadvantage is that when the product is modified, the factory class will also be modified accordingly. such as: How to create and how to provide to clients.

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

Construction Pattern: The product's internal representation and product generation process are separated, so that a build process to generate a different internal representation of product objects. The construction model allows the product interior representation to change independently, and the customer does not have to know the details of the product's internal composition. The construction model can impose a step-by-step construction process.

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

Factory approach mode: The Core factory class is no longer responsible for the creation of all products, but rather the creation of the work into subclasses to become an abstract factory role, only responsible for the specific factory class must implement the interface, and do not contact which product class should be instantiated such details.

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

Original model pattern: 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 pattern allows dynamic additions or decreases to the product class, and the product class does not need to have any predetermined hierarchy, and the original model pattern applies to any hierarchy. 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 family husband Sigleton, they just say "husband", refers to the same person, that is I (just had a dream, which has such a good thing)

Singleton mode: A singleton pattern ensures that a class has only one instance, and instantiates it and supplies the instance singleton pattern to the entire system. The singleton pattern should only be used if there is a real "single instance" requirement.

Structured mode

6, adapter-met a girl at a friend's party Sarah, from Hong Kong, but I do not speak Cantonese, she does not speak Mandarin, had to turn to my friend Kent, he as the ADAPTER between me and Sarah, let me and Sarah can talk to each other ( I don't know if he's going to play me.

Adapter (transformer) mode: Transform the interface of a class into another interface expected by the client, so that two classes that could not work together because of the interface reason mismatch could work together. The adapter class can return a suitable instance to the client according to the parameter.

7, bridge-in the morning to meet the MM, to say good morning, meet mm at night, to say good evening, meet mm wearing a new dress, to say that your clothes beautiful Oh, met mm new hairstyle, to say that your hair is so beautiful oh. Do not ask me "in the morning meet mm new hairstyle How to say" This problem, oneself use bridge combination not on the line

Bridge mode: Decoupling is abstracted and implemented so that they can be changed independently, that is to say, the strong association between them becomes a weak association, which means that the combination/aggregation relationship is used between the abstraction and the implementation of a software system rather than the inheritance relationship, so that the two can be changed independently.

8, composite-mary birthday today. "My birthday, you want to give me a gift." "Well, well, go to the store, you pick it yourself." "This t-shirt is very beautiful, buy, this skirt good-looking, buy, this bag is also good, buy." "Hey, bought three pieces of Ah, I only promised to send a gift of OH." "What Ah, t-shirt plus skirt plus bag, just fit into a set of Ah, MM, trouble you pack up." "" ... ", MM will use composite mode, you will not?"

Synthesis Pattern: A synthetic pattern organizes objects into a tree structure that can be used to describe the relationship between the whole and the part. A synthetic pattern is a pattern that handles the tree structure of an object. The synthesis pattern expresses the relationship of part to the whole with the tree structure. The synthesis pattern allows the client to treat a single Component object and a composite object that is compounded by them in the same way.

9, decorator-mary after the turn to sarly birthday, or don't call her own pick, otherwise this month food will be finished, take out my last year in the summit of the photo, on the back of the "best gift, is to love your Fita", And then to the street gift shop bought a frame (the gift of the MM is also very beautiful OH), then look for the next door to do art design Mike designed a beautiful box to put up ..., we are all decorator, in the end are modifying me this person, how, see understand?

Decorative mode: Decorative mode extends the functionality of the object transparently to the client, an alternative to inheritance and provides more flexibility than inheritance. Dynamically adds functionality to an object that can be undone dynamically. Increase the number of functions that are generated by arranging combinations of some basic functions.

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

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

11, flyweight-every day with mm texting, fingers are exhausted, recently bought a novice machine, you can put some commonly used sentences in the phone, to use, directly take out, in front of the name of MM can be sent, or a word with a word knocked. The shared sentence is the FLYWEIGHT,MM's name, which is the extracted external feature, which is used according to the context.

Henry Mode: Flyweight is the most lightweight in boxing competition. The privilege mode supports a large number of fine-grained objects efficiently in a shared way. The key to share is to distinguish the intrinsic state from the state of the outer Yun. The intrinsic state is stored inside the element and will not vary depending on the environment. The state of the outer Yun is changed with the change of the environment. The external state can not affect the intrinsic state, they are independent of each other. Distinguish between states that can be shared and states that cannot be shared from the general class, and exclude states that cannot be shared from the class. Instead of creating shared objects directly, clients should use a factory object to create objects that are shared. The meta pattern drastically reduces the number of objects in memory.

12, proxy-and mm chat on the internet, a beginning is always "Hi, hello", "Where did you come from?" "How old are you?" "How tall is it?" "These words, really annoying, write a program as my proxy bar, usually received these words are set up an automatic answer, receive other words then notify me to answer, how, cool bar."

Agent Mode: Proxy mode provides a proxy object to an object, and the proxy object controls the reference to the source object. An agent is a person or an agency acting on behalf of another person or an institution. In some cases, the client does not want to or cannot directly refer to an object, and the proxy object can act as a mediator directly between the client and the target object. The client cannot distinguish between the agent subject object and the real subject object. Agent mode can not know the real proxy object, but only hold a proxy object interface, when 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 go to English class, in order to get away to sit in the last row, wow, the front sat several beautiful mm hey, find a note, write "Hi, can do my girlfriend?" If you do not want to please forward ", the note on one after another passed up, bad, to the first row of the MM to pass the note to the teacher, heard is an old maid Ah, run!

Responsibility chain mode: In the chain of responsibility, many objects are referred by each object to the reference of their 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 ultimately processes the request, and the system can dynamically rearrange 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 ultimately not be accepted by any receiving end object.

14, command-I have a mm home tube very strict, unable to meet, had to use her brother in between the two of us to send information, she has any instructions to me, write a note to let her brother bring me. This is not, her brother sent over a command, in order to thank him, I asked him to eat a bowl of miscellaneous sauce noodles, he said: "I also give my sister three boyfriends Send command, on the count you are the most stingy, just please eat noodles." ”,:-(

Command mode: The command mode encapsulates a request or operation into an object. The command mode divides the responsibility for issuing the command from the responsibility of executing the command and delegating it to different objects. The command mode 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 mention how the request was received, and whether the operation was performed, when it was executed, and how it was executed. The system supports the undo of the command.

15, interpreter-I have a "bubble mm canon", above a variety of bubble mm strategy, such as the steps to eat Western food, to see the film method, etc., with the mm date, as long as a interpreter, according to the above script execution on it.

Interpreter pattern: After a given 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 will describe how to interpret these statements using pattern design after having a simple grammar. The language mentioned in the interpreter mode 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 combinatorial rules. Each command object has an interpretation method that represents an explanation of the Command object. Any permutation of objects in the hierarchical structure of a Command object is a language.

16, iterator-I fell in love with Mary, desperate to propose to her.

Mary: "If you want me to marry you, I have to accept my offer."

Me: "I promise you anything," you say.

Mary: "I have a fancy for that one carat diamond."

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

Mary: "I've got a crush on the villa near the lake."

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

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

My head was humming, sitting on the chair, a bite: "I cut, I cut, there are?" ”


Iteration Sub-mode: An iterative subtype can sequentially access elements of a cluster without exposing the internal representation of the aggregation. The aggregate that is formed by the aggregation of multiple objects is a container object capable of accommodating a set of objects. The iteration child mode encapsulates the iteration logic into a separate child object, separating it from the aggregation itself. Iterative sub-schemas simplify the aggregation interface. Each clustered object can have one or more iteration child objects, and the iterative state of each iteration can be independent of each other. Iterative algorithms can be independent of aggregate role changes.

17, mediator-four mm play mahjong, each other who should give who how much money is not clear, thanks to me at that time, in accordance with their own chips count money, earned money from me here, lost money also pay me, everything OK, I got four mm phone.

Mediator pattern: The Mediator pattern wraps a series of objects interacting in such a way that these 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 role of other objects. To ensure that these functions can be changed 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, dealing with the interaction of objects in small scale behavior with those of other objects.

18, memento-at the same time with a few mm chat, must remember what just with mm said some words, or mm found will not happy oh, luckily I have a memo, just with which mm said what I have copied a copy of the memo to save, so you can view the previous record at any time.

Memo Mode: A Memo object is an object that is used to store snapshots of the internal state of another object. The intent of the memo mode is to capture the state of an object without breaking the encapsulation, and to store it so that it can be restored to its stored state in the future when it is appropriate.

19, observer-want to know our company's latest mm information? Joined the company's MM intelligence mail group on the line, Tom is responsible for the collection of intelligence, he found that the new information not one to notify us, directly released to the Mail group, we as subscribers (observers) can receive information in time

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

20, state-and mm intercourse, must pay attention to her state oh, in a different state when her behavior will be different, for example, you ask her to go to the movies tonight, you are not interested in the MM will say "There are things", you do not dislike the MM will say "Yes, but you can take my colleagues?" "What time is it when you have a crush on your mm?" How about going 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 don't like to become like oh."

State mode: state mode allows an object to change behavior when its internal state changes. This object looks like the same class that changed it. The state pattern wraps the behavior of the object 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 allow an object to change its behavior as it changes its internal state. The state pattern requires the creation of a subclass of the State class for each possible state of the system. When the state of the system changes, the system changes the selected subclass.

21, strategy-with different types of mm dating, to use different strategies, some please film better, and some to eat snacks effect is good, and some to the seaside romantic most appropriate, single purpose is to get the heart of MM, my chasing mm kam bag in a lot of strategy oh.

Policy pattern: A policy pattern encapsulates each algorithm into a separate class with a common interface for a set of algorithms so that they can be replaced by each other. The policy pattern allows the algorithm to change without affecting the client. The policy model separates behavior from the environment. Environment classes are responsible for maintaining and querying behavior classes, and various algorithms are provided in specific policy classes. Because the algorithm and environment are independent, the increase or decrease of the algorithm, the modification will not affect the environment and the client.

22, TEMPLATE method--saw the "How to convince girls to go to bed" This classic article? Girls from the understanding to go to bed the same steps are divided into coincidence, break the deadlock, start the pursuit, kiss, foreplay, hands-on, caress, go in eight Steps (Template method), but each step for different situations, there is not the same approach, it depends on you to improvise (concrete);

Template method Pattern: The template method pattern prepares an abstract class, implements part of the logic in the form of concrete methods and constructs, 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 established, and the details of the logic are left to specific subclasses to implement.

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

Visitor mode: The purpose of the visitor pattern is to encapsulate actions that are applied to some data structure element. Once these operations need to be modified, the data structures that accept the operation can remain unchanged. The visitor pattern is suitable for systems with relatively undetermined data structures, which frees up the coupling between the structure and the operations acting on the structure, so that the set of operations can evolve relatively freely. The visitor pattern makes it easy to add new operations, adding a new visitor class. The visitor pattern centralizes the behavior in a visitor object, rather than spreading it into a single node class. When using the visitor pattern, place as many object browsing logic as possible in the visitor class, rather than in its subclasses. The visitor pattern can access the member classes belonging to different hierarchies through the hierarchical structure of several classes.

The above is a small set to introduce the Android design model, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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: 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.