Android four common design patterns
Preface:
The basic design idea of Android development is derived from the java design mode. There are more than N java design modes. According to incomplete statistics, there are about 23 most frequent network occurrences so far. Java is only a development language. It is a required course for every programmer to learn and master the language for code writing. But how to write high-quality, easy-to-maintain, and reusable code, it reflects the programmer's level and level. The design pattern is designed to solve these problems.
When we start to learn the design pattern, we usually have a feeling of complicate the simple problem. Why do we have to create several classes for a class of N lines of code? Abstract and hard to understand. Later, with the growth of development experience and frequent repetitive work, one day I had an epiphany and experienced the wonderful use of the design model. It is often said that experience and time are the best touchstone when everything is done.
1. Factory Model:
What is the factory model? For example, the company has such a requirement that LBS should be used in the App to implement certain functions. There are a lot of product Technologies Beginning with requirements and technical validation sessions. When we discuss whether to use Baidu API or AMAP. There are endless debates. Some people say that Baidu is inaccurate in positioning and some say that autonavi is inaccurate in positioning. There are different opinions. What should I do? Finally, B's total shot board is used together. Which one is useful? The lead shot the board, but did not say it again? What should I do? The factory model is coming soon. I have designed both of them for you, and set a switch and parameter for the Code. If you say it is not good to use AMAP, I will change the parameter to Baidu, the Code was generated until the leader was happy.
Public class test {public static void main (String [] args) {Location position = new LocationFactory (). getInstance ("gaode"); position. getPosition (); position. getCityName (10, 20) ;}} class LocationFactory {public static Location getInstance (String type) {if ("baidu ". equals (type) {return new BaiduLocation () ;}else {return new GaodeLocation () ;}} class BaiduLocation implements Location {@ Override public void getPosition () {// TODO Auto-generated method stub System. out. println ("obtain the current longitude and latitude through Baidu positioning is XXXXX") ;}@ Override public void getCityName (long lat, long lng) {// TODO Auto-generated method stub System. out. println ("the current city obtained through Baidu positioning is XXXXX");} class GaodeLocation implements Location {@ Override public void getPosition () {// TODO Auto-generated method stub System. out. println ("the current longitude and latitude obtained through AMAP positioning is XXXXX") ;}@ Override public void getCityName (long lat, long lng) {// TODO Auto-generated method stub System. out. println ("the current city obtained through AMAP Location is XXXXX") ;}} interface Location {public void getPosition (); public void getCityName (long lat, long lng );}
The above example demonstrates the concept of the factory model. LocationFactory is a factory class. The parameter of the static function getInstance determines Whether Baidu or AMAP is used. In this way, the caller only needs to care about Whether Baidu or AMAP is used. Location is an interface that abstracts common function calls by AMAP and Baidu. For positioning, it is usually used to query the address based on the latitude and longitude, or locate the current location to obtain the latitude and longitude. Of course there may be more useful functions, which I will not list here. With such a common interface, GaodeLocation and BaiduLocation can meet the caller's needs by implementing its interfaces. The caller can change the parameters to meet the needs of different positioning APIs. Of course, if Baidu and autonavi are uncomfortable, you can use Google APIs. You only need to construct a GoogleLocation class and implement the Location interface.
The factory mode is widely used. For example, the BitmapFactory class commonly used in bitmap of android is used to create Bitmap objects. The static factory method is usually used.
2. Singleton mode:
What is Singleton mode? The essence of the singleton mode is mainly in the word "single". "single" is the same and directly enters the topic. We usually use the "new" keyword to create an object, once "new", it will open up the memory to create an object. Suppose that the object we create repeatedly is actually one thing for us, so we don't have to waste resources and time. For example, if you are on a business trip somewhere for at least one day, the first time you go to the service desk, the service desk opens a room for you. You are so happy to go to bed with the key. Go out to work after waking up. After that, did you directly take the key and rush to your room? Should I go to the service center to open another room? Life is a simple model. If you are good at discovering, you will be pleasantly surprised.
Here is an example of boring code.
Public class Room {public static Room key; public static void main (String [] args) {Room room = getKey (); room. openDoor (); Room room1 = getKey (); room1.openDoor ();} public static Room getKey () {if (key = null) {key = new Room ();} return key;} public void openDoor () {System. out. println ("I opened the door ...... ");}}
Let's take a look at the above example. Is it similar to the example of my hotel? This not only saves the hotel time, but also saves your time. In addition, the singleton mode is often used in android development, such as network encapsulation. Database Access uses the standalone design mode.
3. Observer mode:
What is the observer mode? When it comes to the plaintiff, the mind will immediately think of the defendant, and the observer and the respondent will always appear in pairs like the plaintiff and the defendant. The observer mode is also called the subscription mode, with subscribers and publishers. At present, IPHONE6 is very popular. If domestic fans want to purchase it, they must make a reservation. They must go to its apple official website to make a reservation, fill in a lot of information, and I don't know if I don't pay for it. I have to make a reservation for registration. When fans wait for their eyes to be worn and flowers to be thankful, they will be on the stage. The official team will release the product to the fans who have made the reservation with high confidence. This apple is the observer, the fans are the observer, and the contacts between the observer and the observer need to be established, that is, registration. After the registration, when the observer finds that the time is ripe, the system throws an embroidery ball to the observer in the power posture. The observer can't wait to reach out and hold on to the observer, praise Apple's greatness and joy. Staring at the target with a wide eye and looking forward to the expected results, this is the observer pattern.
Laiduan code experience
Import java. util. arrayList; import java. util. list; public class MyOberver {public static void main (String [] args) {American american = new American (); Chinese chinese = new Chinese (); iphone iphone = new Iphone (); System. out. println ("an American Registered purchase"); iphone. register (american); System. out. println ("a Chinese registered purchase"); iphone. register (chinese); try {System. out. println ("after 6 months of long wait... "); Thread. sleep (2000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} iphone. notifys () ;}/ ** Observer */class Iphone {private List
List = new ArrayList
(); Public void register (Fensi n) {list. add (n); System. out. println ("another apple has been reserved. Now there are:" + list. size () + "personal reservation... ");} public void policys () {System. out. println ("IPHONE 6 is on sale now... "); for (Fensi n: list) {n. receive () ;}} class American implements Fensi {@ Override public void receive () {// TODO Auto-generated method stub System. out. println ("The Americans shouted: Well, it's expensive .... ") ;}} class Chinese implements Fensi {@ Override public void receive () {// TODO Auto-generated method stub System. out. println ("Chinese: I finally bought it. I'm so happy to die .... ") ;}} interface Fensi {public void receive ();}
Output result after running:
An American registered to purchase
Another Apple has been reserved, and now there is a total of: 1 person has made a reservation...
One Chinese registered purchase
Another Apple has been reserved. Now there are two people who have made a reservation...
After 6 months of long wait...
IPHONE 6 is on sale now...
The Americans shouted: Well, it's a little expensive ....
Chinese: I finally bought it. I'm so happy to die ....
This is the observer mode. Both Chinese and American are observers. They inherit the Fensi interface and have the ability to receive message receive. Iphone is the observer and the object to be observed, every action of Fensi will deeply affect Fensi's enthusiasm. The observer needs to register and purchase the register where the observer is. After the registration, the observer will take the initiative to send a signal to the iphone when the time is ripe. notifys (); in this way, all fans who have registered to buy Apple 6 will receive the pick-up information one after another.
4. Proxy mode:
What is proxy mode? The proxy mode is widely used in various types of development. It can be seen in j2ee, android, and ios. Therefore, the design mode is everywhere. Proxy mode, which is simply something you cannot do or cannot do. Instead, you must use a third party to achieve your desired purpose or effect. For example, employee Xiao Li is working in company B, and Mr. B is always working for the whole day so that Mr. B cannot work overtime, so Mr. B wants to go to the court to sue Mr. B. Although legal litigation is permitted without a lawyer, self-defense is allowed. But Mr. Li is not familiar with the specific process of legal prosecution. He is stupid in his second mouth, And he shakes badly when he has more than one leg. Therefore, Mr. Li decided to seek help from a legal representative. Compared with your own lawsuit, you can find a legal representative in the same and different places.
In the same way:
1. You must submit the plaintiff's information, such as name, age, reason, and purpose.
2. They all need to go through the Court's forensic investigation, court session debate, and other processes.
3. Finally, get the trial result.
The difference is:
1. Xiao Li saves time and allows professional people to do professional things without having to learn about the complicated process of the Court.
2. better grasp.
Through the above example, we noticed that the proxy mode has several key points.
1. Proxy role (Xiao Li)
2. proxy roles (lawyers)
3. Protocol (whatever the proxy or the person who is being acted on, what needs to be done is abstracted as a protocol)
The following is an example:
Public class Proxy {public static void main (String [] args) {Employer employer = new Employer (); System. out. println ("I can't stand it anymore. I'm going to file a lawsuit with my boss"); System. out. println ("Ask a lawyer to solve it ...... "); Protocol lawyerProxy = new LawyerProxy (employer); lawyerProxy. register ("Blossoming Flowers"); lawyerProxy. dosomething (); lawyerProxy. notifys () ;}} interface Protocol {// Registration Information public void register (String name); // investigate the case and file a lawsuit public void dosomething (); // After the lawsuit is completed, inform the Employer of public void policys ();} // lawyer class LawyerProxy implements Protocol {private employer Employer; public LawyerProxy (employer Employer) {this. employer = employer;} @ Override public void register (String name) {// TODO Auto-generated method stub this. employer. register (name);} public void collectInfo () {System. out. println ("as a lawyer, I need to sort out and investigate based on the information provided by the employer, write a written letter to the court, and provide evidence. ") ;}@ Override public void dosomething () {// TODO Auto-generated method stub collectInfo (); this. employer. dosomething (); finish ();} public void finish () {System. out. println ("this lawsuit has been completed ............... ") ;}@ Override public void policys () {// TODO Auto-generated method stub this. employer. notifys () ;}// Employer class Employer implements Protocol {String name = null; @ Override public void register (String na Me) {// TODO Auto-generated method stub this. name = name ;}@ Override public void dosomething () {// TODO Auto-generated method stub System. out. println ("I am '" + this. name + "'I want to tell Mr. B that he keeps working overtime and has no overtime. ") ;}@ Override public void policys () {// TODO Auto-generated method stub System. out. println ("the court ruled that B must pay 0.1 million yuan in compensation for mental compensation if the lawsuit wins. ");}}
After running, print as follows:
I can't stand it anymore. I'm going to file a lawsuit with my boss.
Ask a lawyer to solve the problem ......
As a lawyer, I need to sort out and investigate based on the information provided by the employer, write a written letter to the court, and provide evidence.
I want to tell Mr. B that he keeps working overtime and there is no overtime fee.
This lawsuit has been completed ...............
The Court ruled that B must pay 0.1 million yuan in compensation for mental compensation if the lawsuit wins.
Code Description:
The Protocol class is the Protocol mentioned above. It is an agreement that is jointly observed by the agent or the agent. That is to say, what must be done whether the plaintiff or an Attorney-General goes to the Court to go through the procedures. This is the protocol.
Employer is also known as the agent class of the Employer class. It complies with the Protocol, implements three methods of the Protocol, and completes specific tasks respectively.
LawyerProxy is a proxy class, which also complies with the Protocol. Unlike Employer, an Employer object is defined and initialized through the constructor. In the three methods implemented, the same Implementation of the proxy class is called respectively. It is like simulating a defendant, standing in the defendant's perspective, and going to the court to complain. That is to say, the LawyerProxy agent class is open to anyone who wants to file a lawsuit. As long as the plaintiff comes in, I will help him to file a lawsuit. It is worth noting that collectInfo and finish are two functions. If you ask a lawyer to file a lawsuit or not ask a lawyer to file a lawsuit, you have to do the same thing (register, dosomething, policys). But why? Didn't you say that? The benefit of asking a lawyer is that he is considerate and professional. He will collect collectInfo on the premise of doing the same thing ), and the processing of subsequent tasks (finish ).
The above is the most common proxy mode. By extension, we can see that for the defendant, an Employer class must be created and passed to the LawyerProxy proxy class after being instantiated, is Employer exposed? What should we do if we hide it as a more intelligent and dummies for the defendant?
Public class Proxy {public static void main (String [] args) {// Employer employer = new Employer (); System. out. println ("I can't stand it anymore. I'm going to file a lawsuit with my boss"); System. out. println ("Ask a lawyer to solve it ...... "); Protocol lawyerProxy = new LawyerProxy (" Blossoming Flowers "); lawyerProxy. dosomething (); lawyerProxy. notifys () ;}} interface Protocol {// Registration Information public void register (String name); // investigate the case and file a lawsuit public void dosomething (); // the lawsuit is completed, notify the employer public void notif Ys ();} // lawyer class LawyerProxy implements Protocol {private Employer employer; public LawyerProxy (String name) {if (name = null) {System. out. println ("Who complained? Are you kidding me? "); Return;} if (employer = null) employer = new Employer (); register (name) ;}@ Override public void register (String name) {// TODO Auto-generated method stub this. employer. register (name);} public void collectInfo () {System. out. println ("as a lawyer, I need to sort out and investigate based on the information provided by the employer, write a written letter to the court, and provide evidence. ") ;}@ Override public void dosomething () {// TODO Auto-generated method stub collectInfo (); this. employer. dosomething (); finish ();} public void finish () {System. out. println ("this lawsuit has been completed ............... ") ;}@ Override public void policys () {// TODO Auto-generated method stub this. employer. notifys () ;}// Employer class Employer implements Protocol {String name = null; @ Override public void register (String na Me) {// TODO Auto-generated method stub this. name = name ;}@ Override public void dosomething () {// TODO Auto-generated method stub System. out. println ("I am '" + this. name + "'I want to tell Mr. B that he keeps working overtime and has no overtime. ") ;}@ Override public void policys () {// TODO Auto-generated method stub System. out. println ("the court ruled that B must pay 0.1 million yuan in compensation for mental compensation if the lawsuit wins. ");}}
No new LawyerProxy ("Blossoming Flowers") is displayed. You only need to input a simple name to the proxy class, which implies the Employer class. The proxy class will automatically create an Employer instance, simulate a user to continue to complete the lawsuit for you.
Limited space, there are many design patterns. The above lists several common ones and the most commonly used ones. I hope you can understand and master them. If you are interested, for more information, see Zen of design patterns.