Design patterns in Android

Generally speaking, there are eight common design patterns: singleton, factory, observer, agent, command, adapter, synthesis and visitor

Singleton mode: the purpose is to make the system have only one calling object. The disadvantage is that singleton makes other programs rely too much on it, and different singletons run in different processes, making maintenance difficult;

Factory mode: it produces fixed things, such as abstract classes. The disadvantage is that it is troublesome to modify products; For example, people who like action movies and love movies send the same request to the server, they can get the movie collection they want to see, which is equivalent to different objects making the same request, and their needs are met.

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

Proxy mode: leave your own affairs to others and return the results respectively, such as asynchronous thread;

Command mode: the calling object and the acting object are separated, and the middleware coordinates the work between them, such as the controller;

Adapter mode: turn an interface into the interface required by users. For example, base adapter can adapt to listview and spinner because they have the same interface

Synthesis mode: convert one to many relationship into one to whole relationship, such as listview and adapter;

Visitor mode: different objects are handled differently, such as instanceof.

A friend on the Internet explained the design pattern very interesting, so he excerpted it below, but he couldn't find the original author, so please forgive me for not adding the original address!

Create pattern

1. Factory - after mm, we have to invite him to dinner. McDonald's chicken wings and KFC chicken wings are MM's favorite food. Although the taste is different, no matter you take mm to McDonald's or KFC, just say "four chicken wings" to the waiter. McDonald's and KFC are factories that produce chicken wings

Factory mode: customer class and factory class are separated. Whenever consumers need a product, they just need to ask the factory for it. Consumers can accept new products without modification. The disadvantage is that when the product is modified, the factory class also needs to be modified accordingly. For example, how to create and provide to the client.

2. Builder - mm's favorite is the sentence "I love you". When you see mm in different places, you should be able to say this sentence to her in their dialect. Oh, I have a multilingual translator with a button in each language. When you see mm, as long as I press the corresponding button, it can say the sentence "I love you" in the corresponding language, and foreign mm can easily deal with it, This is my "I love you" builder. (this must be better than the translation machine used by the U.S. military in Iraq)

Construction mode: separate the internal representation of the product from the product generation process, so that a construction process can generate product objects with different internal representations. The construction mode allows the internal appearance of the product to change independently, and customers do not need to know the details of the internal composition of the product. The construction mode can enforce a step-by-step construction process.

3. Factory method - invite mm to McDonald's for hamburgers. Different mm have different tastes. It's annoying for everyone to remember. I usually use the factory method mode, take mm to the waiter and say "want a hamburger". What kind of hamburger do you want? Just let mm tell the waiter directly.

Factory method mode: the core factory class is no longer responsible for the creation of all products, but hands over the specific creation work to the subclasses to become an abstract factory role. It is only responsible for giving the interface that the specific factory class must implement, without touching the details of which product class should be instantiated.

4. Prototype - when chatting with mm on QQ, I must say some affectionate words. I have collected a lot of tender love words. If necessary, just copy them out and put them in QQ. This is my love word prototype. (100 yuan a share, would you like it)

Original model pattern: 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 mode allows dynamic addition or reduction of product categories. Product categories do not need to have any predetermined hierarchical structure. The original model mode is applicable to any hierarchical structure. The disadvantage is that each class must be equipped with a cloning method.

5. Singleton - I have six beautiful wives. Their husbands are all me. I am sigleton, the husband of our family. As long as they say "husband", they all refer to the same person, that is me (just had a dream, how can there be such a good thing)

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

Structural model

6. Adapter - I met a beautiful Sarah from Hong Kong at a friend's party, but I can't speak Cantonese. She can't speak Mandarin, so I had to turn to my friend Kent. As the adapter between me and Sarah, Sarah and I can talk to each other (I don't know if he will play with me)

Adapter (transformer) mode: transform the interface of a class into another interface expected by the client, so that the two classes that cannot work together due to interface mismatch can work together. The adaptation class can return an appropriate instance to the client according to the parameters.

7. Bridge - if you meet mm in the morning, say good morning, and if you meet mm in the evening, say good evening; When you meet mm wearing a new dress, you should say that your clothes are so beautiful. When you meet MM's new hairstyle, you should say that your hair is so beautiful. Don't ask me the question "how to say when I met mm with a new hairstyle in the morning". Just combine it with bridge

Bridge mode: decouple abstraction and realization, so that they can change independently, that is, turn their strong association into weak association, that is, use combination / aggregation relationship instead of inheritance relationship between abstraction and Realization of a software system, so that they can change independently.

8. Pose -- Mary's birthday today. "You want to give me a present for my birthday." "Well, well, go to the store and choose for yourself." "This T-shirt is very beautiful. Buy it. This skirt looks good. Buy it. This bag is also good. Buy it." "Hey, I bought three. I only promised to give one gift." "What, T-Shirts, skirts and bags just match into a set, mm, please wrap it up." "...", mm can use composite mode, can you?

Composite pattern: composite pattern organizes objects into a tree structure, which can be used to describe the relationship between whole and part. A composite pattern is a pattern that deals with the tree structure of objects. The composition pattern expresses the relationship between part and whole in a tree structure. The composition mode enables the client to treat individual component objects as the composite objects composed of them.

9. Decorator - after Mary's birthday, it's sarly's turn. Don't ask her to choose by herself, otherwise the food expenses will be finished this month. Take out the photo I took on the top of Huashan last year, write "the best gift is FITA who loves you" on the back, and then buy a picture frame in the street gift shop (MM who sells gifts is also very beautiful), Find Mike, who is engaged in art design next door, and design a beautiful box to put it in... We are all decorators, and we are finally decorating me. How do you understand?

Decoration mode: Decoration mode extends the functions 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, which can be dynamically undone. Add a very large number of functions generated by the arrangement and combination of some basic functions.

10. Facade - I have a professional Nikon camera. I like to manually adjust the aperture and shutter so that the photos taken are professional, but mm doesn't understand these and can't teach for a long time. Fortunately, the camera has a facade design mode. Adjust the camera to automatic. Just aim at the target and press the shutter. Everything is automatically adjusted by the camera, so mm can take a picture of me with this camera.

Facade mode: external communication with a subsystem must be carried out through a unified facade object. Facade mode provides a high-level interface, which makes the subsystem 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. However, the whole system can have multiple facade classes.

11. Flyweight - I'm tired of sending text messages to mm every day. I recently bought a new mobile phone. I can store some commonly used sentences in the mobile phone. When I want to use them, I can take them out directly and add MM's name in front of them to send them. I don't have to type 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.

Enjoy yuan mode: flyweight refers to the lightest weight in boxing competition. The shared meta model efficiently supports a large number of fine-grained objects in a shared way. The key of sharing meta model is to distinguish intrinsic state and extrinsic state. The intrinsic state is stored in the element and will not change with the change of the environment. The intrinsic state changes with the change of environment. The intrinsic state cannot affect the intrinsic state. They are independent of each other. Distinguish the shareable state from the unsharable state from the regular class, and eliminate the unsharable state from the class. Instead of directly creating shared objects, the client should use a factory object to create shared objects. The meta mode greatly reduces the number of objects in memory.

12. Proxy - chatting with mm on the Internet always starts with "Hi, hello" and "where are you from?" "How old are you?" "How tall?" These words are really annoying. Write a program as my proxy. If you receive these words, you have set up automatic answers. When you receive other words, you will inform me to answer. How cool.

Proxy mode: 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 organization acting on behalf of another person or an organization. In some cases, the client does not want or cannot directly reference an object. The proxy object can directly mediate 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 proxy object, but only hold an interface of the proxy object. At this time, the proxy object cannot create the proxy object, and the proxy object must be created and passed in by other roles of the system.

Behavior pattern

13. Chain of responsibility -- I went to English class in the evening and sat in the last row for a good slip. Wow, there were several beautiful MM sitting in front. Hey, find a note and write "Hi, can you be my girlfriend? If you don't want to pass it forward", and the notes were passed one by one. No, it was passed to the mm in the first row and passed the note to the teacher, I heard it's an old maid. Run!

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

To form a chain. Requests are passed along the chain until an object in the chain decides to process the request. The client does not know which object in the chain will eventually handle the request. The system can dynamically reorganize the chain and allocate responsibilities without affecting the client. The processor has two choices: take responsibility or shift the responsibility to the next family. A request can eventually not be accepted by any receiver object.

14. Command - I have a MM who is very strict at home and can't meet. I have to send information between us with the help of her brother. If she has any instructions for me, she will write a note for her brother to bring to me. No, her brother sent another command. In order to thank him, I invited him to eat a bowl of miscellaneous sauce noodles. Unexpectedly, he said, "I sent commands to my sister's three boyfriends at the same time. Just count your cheapness and invite me to eat noodles."- (

Command mode: command mode encapsulates a request or operation into an object. Command mode separates the responsibility of issuing commands from the responsibility of executing commands and delegates them to different objects. The command mode allows the requesting party and the sending party to be independent, so that the requesting party does not have to know the interface of the receiving party, let alone how the request is received, whether the operation is executed, when it is executed and how it is executed. The system supports command undo.

15. Interpreter - I have a "bubble mm Sutra", which contains various strategies for bubble mm, such as the steps to eat Western food, the methods to go to the movies, etc. when dating mm, just make an interpreter and follow the script above.

Interpreter pattern: 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 sentences in this language. The Interpreter pattern describes how to interpret these statements using pattern design after having a simple grammar. The language mentioned in the Interpreter pattern refers to any combination that can be interpreted by any interpreter object. In the interpreter mode, you need to define a hierarchical structure of command classes representing grammar, that is, a series of combination rules. Each command object has an interpretation method that represents the interpretation of the command object. Any permutation of objects in the hierarchy of command objects is a language.

16. Iterator - I fell in love with Mary and proposed to her recklessly.

Mary: "if you want me to marry you, you have to promise my terms"

Me: "I promise everything, you say it"

Mary: "I'm interested in that carat of the diamond."

Me: "I buy, I buy, anything else?"

Mary: "I like the villa by the lake"

Me: "I buy, I buy, anything else?"

Mary: "your little brother must be 50cm long."

With a buzzing sound in my head, I sat on the chair and gritted my teeth: "I cut, I cut, is there anything else?"

……

Iterative sub pattern: the iterative sub pattern can access the elements in an aggregation sequentially without exposing the internal appearance of the aggregation. The aggregate formed by multiple objects is called aggregation. The aggregation object is a container object that can contain a group of objects. The iteration sub pattern encapsulates the iteration logic into a separate sub object, which is separated from the aggregation itself. The iterative sub pattern simplifies the interface of aggregation. Each aggregation object can have one or more iteration sub objects, and the iteration states of each iteration sub object can be independent of each other. The iterative algorithm can be independent of aggregation role changes.

17. Media - four mm play mahjong. It's not clear who should give whom and how much money to each other. Fortunately, I was nearby and calculated the money according to their respective chips. Those who made money took it from me and those who lost money paid me. Everything was OK. I got the phone number of four mm.

Mediator pattern: the mediator pattern wraps the way a series of objects interact so that they do not have to interact significantly. So that they can be loosely coupled. When the interaction between some objects changes, it will not immediately affect the interaction between other objects. Ensure that these functions can change independently of each other. The mediator model transforms many to many interactions into one to many interactions. The mediator model abstracts the behavior and cooperation of objects, and processes the interaction between objects and other objects on a small scale.

18. Memento - when chatting with several mm at the same time, be sure to remember what you just said to mm, otherwise mm will be unhappy if you find it. Fortunately, I have a memo. I copy what you just said to mm and keep it in the memo, so that you can check the previous records at any time.

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

19. Observer - do you want to know the latest mm information of our company? Just join the MM information e-mail group of the company. Tom is responsible for collecting information. He doesn't need to notify us one by one of the new information he finds. He will directly publish it to the e-mail group. As subscribers (observers), we can receive the information in time

Observer mode: the observer mode defines a dependency relationship of one team and multiple observers, which allows multiple observer objects to listen to a topic object at the same time. When the subject object changes in state, it will notify all observer objects so that they can update themselves automatically.

20. State - when communicating with mm, be sure to 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, MM who is not interested in you will say "something's up", and MM who is not annoying but doesn't like you will say "OK, but can you bring my colleagues?", MM who has fallen in love with you will say "what time? How about going to the bar after watching the film?", Of course, if you perform well in the process of watching movies, you can also turn MM's state from dislike to like.

State mode: state mode allows an object to change its behavior when its internal state changes. This object looks like it has changed its class. The state pattern packages the behavior of the studied object in different state objects, and each state object belongs to a subclass of an abstract state class. The intention of state pattern is to make an object change its behavior when its internal state changes. State mode needs to create a subclass of state class for each possible state of the system. When the state of the system changes, the system changes the selected subclass.

21. Strategy - different strategies should be used to date different types of mm. Some invite movies, some go to eat snacks, and some go to the seaside for romance. The single purpose is to get MM's heart. There are many strategies in my pursuit of mm.

Policy pattern: for a group of algorithms, the policy pattern encapsulates each algorithm into an independent class with a common interface, so that they can replace each other. The policy pattern allows the algorithm to change without affecting the client. The strategy pattern separates behavior from environment. The environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in specific policy classes. Since the algorithm is independent of the environment, the increase, decrease and modification of the algorithm will not affect the environment and the client.

22. Template method -- have you read the classic article "how to persuade girls to go to bed"? The constant steps for girls to go to bed can be divided into eight template methods: chance encounter, breaking the deadlock, pursuing, kissing, foreplay, hands-on, caressing and going in. However, each step has different practices for different situations, which depends on your random response (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 the subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, so as to have different implementations of the remaining logic. First develop a top-level logic framework, and leave the details of logic to specific subclasses to implement.

23. Visitor - Valentine's Day is coming. We should send each mm a bunch of flowers and a card, but the flowers sent by each mm should be based on her personal characteristics, and each card should also be selected according to her personal characteristics. I can't figure it out. I'd better ask the florist and gift shop owner to be a visitor and let the florist choose a bunch of flowers according to the characteristics of mm, Let the gift shop owner choose a card according to everyone's characteristics, which is much easier;

Visitor pattern: the purpose of visitor pattern is to encapsulate some operations imposed on certain data structure elements. Once these operations need to be modified, the data structure accepting the operation can remain unchanged. Visitor pattern is suitable for systems with relatively uncertain data structure. It separates the coupling between data structure and operation on structure, so that the operation set can evolve relatively freely. Visitor mode makes it easy to add new operations, that is, to add a new visitor class. Visitor pattern centralizes the relevant behaviors into one visitor object rather than scattered into node classes. When using visitor mode, put as much object browsing logic as possible in the visitor class, not in its subclasses. The visitor pattern can access member classes belonging to different hierarchies across several class hierarchies.

The above is the design mode in Android introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>