Description of Android four common design patterns

Source: Internet
Author: User

Preface :

Android development of the design pattern, the basic design ideas from the Java design pattern, Java design pattern has n many, incomplete statistics, so far, the network appears the most frequent about 23 kinds. Java is just a development language, learning and mastering the language for code writing, which is required for each programmer, but how to write high-quality, easy to maintain and reusable code, that reflects the level of the programmer and level. Design patterns appear to solve these problems.

When we started to learn design patterns, we usually had the feeling of complicating the simple problem, and clearly what a class n line of code would do, why not create several classes? Abstract and difficult to understand. Later, with the development experience growth, repeated labor frequently, one day epiphany, experience the magic of design patterns, fang filled with emotion. Saying goes, stones, doing anything is like this, experience and time are the best touchstone.

1. Factory mode :

What is a factory model? For example, the company has a need to use the LBS location in the app to implement certain functions. Product technology A lot of the beginning of the demand, technical confirmation, when we discussed the positioning is to use Baidu API to achieve, or with high-tech to achieve. We are arguing that some people say that Baidu positioning is not allowed, some people say that the position is not allowed, divergent opinions. Do how Finally, b Total decision, two together, which is easy to use which, the leadership of the decision, but said that is equal to not say, how to do? Factory mode At this time, I have to give you two design, code set a switch and parameters, you say with the bad, I changed a parameter, Baidu, until the leadership happy, so the code produced.  

public class Test {public static void main (string[] args) {location position= new Locationfactory (). g              Etinstance ("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 ("Through Baidu positioning to obtain to the current latitude and longitude is xxxxx");              } @Override public void Getcityname (long lat, long LNG) {//TODO auto-generated method stub       System.out.println ("Through Baidu positioning to get to the current city is xxxxx"); }}class Gaodelocation implements location{@Override public void getPosition () {//TODO Auto-gen EratEd method Stub System.out.println ("Obtains to the current latitude and longitude through the German position is xxxxx");              } @Override public void Getcityname (long lat, long LNG) {//TODO auto-generated method stub       System.out.println ("Get to the current city through the German positioning is xxxxx");       }}interface location{public void getPosition (); public void Getcityname (long Lat,long LNG);}

The above example is a good illustration of the concept of a factory model. Locationfactory is a factory class, the parameters of the static function getinstance decide whether to choose Baidu or high, so, for the caller, only need to care about you are using Baidu or gold can. Location is an interface that abstracts the function calls that are commonly used by both German and Baidu. For positioning, it is generally used to query the address according to latitude and longitude, or locate the current location to obtain latitude and longitude. Of course there may be more useful functions, and I'm not listing them here. With such a common interface, gaodelocation and baidulocation can satisfy the caller's needs by implementing its interface. The caller is able to arbitrarily change the parameters to implement the requirements from different positioning APIs. Of course, if Baidu and the German bad, you can use the Google API, only need to construct a googlelocation class and implement the location interface method.

Factory mode is widely used, such as the Bitmapfactory class commonly used in Android bitmap, to create bitmap objects, often using static factory methods.

2. Singleton mode:

What is a singleton mode? The essence of the singleton mode is mainly in this "single" Word, "single" is a, directly into the topic, we usually use the "new" keyword to create an object, once "new", it will open up memory to create an object. Assuming that we often create this object repeatedly is the same thing for us, then we do not need to waste resources and time, like, you go to travel somewhere in a place for at least 1 days, the first time you go to the desk, the desk to open a room, you happily with the key into the room to sleep. Wake up and go out and do errands. When you're done, are you going straight to your open room with this key? Is it time to go to the desk and open a room? Avenue to Jane, in fact, carefully want to think, life is a model, as long as you are good at discovering, you will have unexpected surprises, the original is so simple.

Let's take an example, the boring code.

public class (Public       ) (public static)       public static void Main (string[] args) {              room=getkey ();              Room.opendoor ();              Room1=getkey ();              Room1.opendoor ();        }       public static GetKey () {              if (key==null) {                     key=new) ();              }              Return key;       }        public void Opendoor () {              System.out.println ("I opened the door ...");}       

Look at the example above, is it similar to the example I gave to the hotel? To do so, both save the time of the hotel, but also save your time, how good ah. Further, it is often used in Android development to use a singleton pattern, such as the encapsulation of the network and the access of the database to the simple interest design pattern.

3. Observer Mode:

What is the Observer pattern? Generally referred to the plaintiff, the inevitable brain immediately associated with the defendant, the observer and the Observer as the plaintiff and the defendant are always so in the right to appear. The observer pattern, also called the subscription pattern, has subscribers and publishers. Now IPHONE6 unusually hot, domestic fans want to buy, that must be booked, must go to it Apple official to book, fill a lot of information, pay no money I do not know, anyway have to book registration. When the fans wait for two eyes to wear, the flowers quickly thanked, it came into the show, the official high-profile calmly to the scheduled fans on sale. The Apple is the observer, the fan is the Observer, the observer and the observer need to establish a connection, that is, registration. After the registration, the observer to grasp the heat when the time is ripe, to the position of the attitude of the observer throw hydrangea, the observer can not wait to reach out their hands firmly grasped, filled with joy praise the great apple and their own blessings. Staring at the target with wide eyes, expecting the desired result, this is the observer pattern.

To a snippet of 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 to buy");               Iphone.register (American);               System.out.println ("A Chinese registered to buy");               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.printstack              Trace ();       } Iphone.notifys ();       }}/** Observer */class iphone{private list<fensi> list=new arraylist<fensi> ();              public void Register (fensi N) {list.add (n);       System.out.println ("Another Apple has been booked, now there are:" +list.size () + "personal booking ..."); } public void NOTIFYs () {System.out.println ("IPHONE 6 now High-profile sale ...");              for (Fensi n:list) {n.receive (); }}}class American implements fensi{@Override public void receive () {//TODO Auto-generat       Ed method Stub System.out.println ("The Americans shout: Hum, a little expensive ..."); }}class Chinese implements fensi{@Override public void receive () {//TODO auto-generated Metho       D stub System.out.println ("Chinese: I finally bought, happy dead ..."); }}interface fensi{public void receive ();

Post-run output results:

An American registered to buy

Another Apple has been booked, now total: 1 people booked ...

A Chinese registered to buy

Another Apple has been booked, now total: 2 people booked ...

After 6 months of long wait ...

IPHONE 6 is now on high-profile sale ...

The Americans shouted: Hmm, a little expensive ....

Chinese: I finally bought, happy dead ....

This is the observer pattern, Chinese and American are observers, they inherit the Fensi interface, with the ability to receive message receiving, the iphone is the Observer, is the target of observation, it's every move, it will deeply affect the enthusiasm of the Fensi people, The observer needs to register with the observer where it is registered, and when the time is ripe, the observer will take the initiative to emit the Signal iphone.notifys (), so that all fans who have registered for Apple 6 will receive a pickup message.

4. Proxy mode:

What is proxy mode? The agent mode is widely used in various kinds of development, whether it is j2ee,android or iOS, can see its figure, so that design patterns everywhere. The proxy mode, the literal understanding is oneself inconvenient to do or cannot do the thing, needs the third party to do, finally through the third party to achieve oneself wants the goal or the effect. For example: Employee Xiao Li in the B head office work, b always let Xiao Li overtime not to pay overtime, Xiao Li can't bear, just want to go to court to sue B total. Although legally allowed to litigate does not invite lawyers to allow self-defense. But Xiao Li is not familiar with the specific process of legal prosecution, the second mouth is more stupid, people a lot of legs shaking badly. Therefore, Xiao Li decided to find a lawyer to help the lawsuit. There are different places and places for lawyers to sue and to litigate.

The same place is:

1, all need to submit the plaintiff's information, such as name, age, cause of the matter, want to achieve the purpose.

2, all need to go through the forensic investigation, court debate and other processes.

3. Finally get the result of the trial.

Different places are:

1, Xiao Li Easy, so that professional people do professional things, do not need to understand the court that a set of cumbersome and complex process.

2, grasp the greater.

From the above example, we note that the proxy pattern has several key points.

1, the role of the agent (Xiao Li)

2. Acting Role (lawyer)

3, the agreement (whether agents and agents who do, all need to do things, abstract out is the agreement)

Here's an example:

public class Proxy {public static void main (string[] args) {employer employer=new employer ();              System.out.println ("I can't stand it, I want to sue the Boss");              System.out.println ("Get a lawyer to solve it ...");              Protocol lawyerproxy=new lawyerproxy (employer);              Lawyerproxy.register ("blossoming flowers");              Lawyerproxy.dosomething ();       Lawyerproxy.notifys ();       }}interface protocol{//Register Data public void Register (String name);       Investigation case, litigation public void dosomething (); The lawsuit is completed, notify the employer public void NOTIFYs ();}       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 t       His.employer.register (name); } public void Collectinfo () {System.out.println ("as a lawyer, I need to organize and investigate according to the information provided by the employer, write to the court writtenText, and provide evidence.       "); } @Override public void dosomething () {//TODO auto-generated method stub Collectin              Fo ();              This.employer.dosomething ();       Finish ();         } public void Finish () {System.out.println ("This lawsuit has been finished ....."); } @Override public void NOTIFYs () {//TODO auto-generated method stub This.employer       . NOTIFYs ();       }}//Employer Class Employer implements protocol{String Name=null; @Override public void Register (String name) {//TODO auto-generated method stub this.name       =name; } @Override public void dosomething () {//TODO auto-generated method stub System. Out.println ("I Am" "+this.name+" to sue B Total, he keeps me working overtime every day, there is no overtime pay.       "); } @Override public void NOTIFYs () {//TODO auto-generated method stub System.out. println ("the court ruled that the lawsuit won, b total compensation for 100,000 yuanMental compensation fee.       "); }        }

After running, print as follows:

I'm going to sue the boss for a lawsuit.

Ask a lawyer to solve it ...

As a lawyer, I need to collate and investigate the information provided by the employer, write a written letter to the court and provide evidence.

I am ' blossoming flower ' to sue B Total, he keeps me working overtime every day, there is no overtime pay.

This lawsuit has been finished ...... .....

The court ruled that the lawsuit won, b always need to compensate 100,000 yuan spiritual compensation fee.

Code Description:

Protocol This class is the above mentioned protocol, is the agent or agent to abide by the agreement. That is to say, whether the plaintiff or the attorney, to the court to go through the procedure, all need to do. We abstracted it, and this is the agreement.

Employer This category is the Employer class, also known as the Agent class, it complies with the Protocol Protocol, and implements the Protocol Protocol of three methods, and to accomplish the specific things separately.

Lawyerproxy This class is a proxy class, and it complies with the Protocol protocol, unlike employer, which defines a employer object that is initialized by a constructor function. In the implementation of the three methods, respectively, to invoke the same implementation of the proxy class. It is like going to mock a defendant, standing on the defendant's point of view and going to court to complain. That is to say, Lawyerproxy proxy class for all who want to sue Open, as long as the plaintiff came in, I will help him sue. It is noteworthy that the two functions of collectinfo and finish, the lawyer to sue and not to sue, in fact, do the same thing (register, dosomething, NOTIFYs), but why? Did you say that the benefit of the lawyer is worry and professional, he will collect the evidence and information (Collectinfo) that is advantageous to you, and the processing of the follow-up (finish) under the premise of doing the same thing.

Above is the most common proxy mode, extending a point, we see, for the defendant, must create a employer class, and instantiate after the argument to the Lawyerproxy proxy class, this is not a burst of employer? If hidden, for the defendant, more intelligent fool a bit, how to do it?

public class Proxy {public static void main (string[] args) {//employer employer=new employer ();              System.out.println ("I can't stand it, I want to sue the Boss");              System.out.println ("Get a lawyer to solve it ...");               Protocol lawyerproxy=new lawyerproxy ("Blossoming bloom");              Lawyerproxy.dosomething ();       Lawyerproxy.notifys ();       }}interface protocol{//Register Data public void Register (String name);       Investigation case, litigation public void dosomething (); The lawsuit is completed, notify the employer public void NOTIFYs ();}       Lawyer Class Lawyerproxy implements protocol{private employer employer; Public Lawyerproxy (String name) {if (name==null) {System.out.println ("who sued?") You kidding me?                     ");              Return              } if (Employer==null) employer=new employer ();        Register (name); } @Override public void Register (String name) {//TODO auto-generated method stub t His.empLoyer.register (name); } public void Collectinfo () {System.out.println ("as a lawyer, I need to collate and investigate the information provided by the employer, write the written text to the court and provide evidence.")       "); } @Override public void dosomething () {//TODO auto-generated method stub Collectin              Fo ();              This.employer.dosomething ();       Finish ();         } public void Finish () {System.out.println ("This lawsuit has been finished ....."); } @Override public void NOTIFYs () {//TODO auto-generated method stub This.employer       . NOTIFYs ();       }}//Employer Class Employer implements protocol{String Name=null; @Override public void Register (String name) {//TODO auto-generated method stub this.name       =name; } @Override public void dosomething () {//TODO auto-generated method stub System. Out.println ("I Am" "+this.name+" to sue B Total, he keeps me working overtime every day, there is no overtime pay.       ");   } @Override    public void NOTIFYs () {//TODO auto-generated Method Stub System.out.println ("The court ruled that the lawsuit won, B always required To compensate for the spiritual compensation of $100,000.       "); }        }

See no new Lawyerproxy ("Blossoming flower"), only need to give the proxy class to pass in a simple name, implied employer class, proxy class will automatically go to create a employer instance, simulate a user to continue to complete the lawsuit for you.
Space is limited, there are many design patterns, the above list of several commonly used, but also the most commonly used the most basic of several, I hope you can understand and master, if interested, please refer to the "design mode of Zen" This book, personal feel good.

Description of Android four common design patterns

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.