An explanation of common Android design patterns

Source: Internet
Author: User
<span id="Label3"></p><p><p><strong>Preface</strong> :</p></p><p><p>The design pattern of the Android development, the basic design idea originates from the Java design pattern, the Java design pattern has n many, incomplete statistics, so far, the network appears the most frequently 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.</p></p><p><p>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, do anything is so, experience and time is the best touchstone, b elder brother old, precedent, after the car Division. Gossip less, then turn to the point, we introduce the common design patterns.</p></p><p><p></p></p><p><p><strong>Factory mode</strong> :</p></p><p><p>What is a factory model? The official has a lot of explanations, I here I understand the combination of experience, interpretation to everyone, I do not want to racked my brains, abstract summed up similar to the ancient prose (java programming Ideas) as difficult to understand the text, nor that level concise, sharply summed up all sentient beings can understand the Explanation. Can only clumsy birds have, qinnengbuzhuo, from the practice of genuine knowledge of the point of view, for everyone to Think. 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.</p></p><p><p></p></p><p>public class Test {<br>public static void main (string[] Args) {<br>Location position= new Locationfactory (). getinstance ("xiaomi");<br>Position.getposition ();<br>Position.getcityname (10, 20);<br>}<br>}<br> <br>Class locationfactory{<br>public static location getinstance (String Type) {<br>If ("baidu". equals (type)) {<br>return new Baidulocation ();<br>}else {<br>return new Xiaomilocation ();<br>}<br>}<br>}<br>Class Baidulocation implements location{<br>@Override<br>public void GetPosition () {<br>TODO auto-generated Method Stub<br>System.out.println ("through Baidu Positioning to obtain the current latitude and longitude is xxxxx");<br>}<br>@Override<br>public void Getcityname (long lat, long Lng) {<br>TODO auto-generated Method Stub<br>System.out.println ("through Baidu positioning to get to the current city is xxxxx");<br>}<br>}<br>Class Xiaomilocation implements location{<br>@Override<br>public void GetPosition () {<br>TODO auto-generated Method Stub<br>System.out.println ("the current latitude and longitude through millet positioning is xxxxx");<br>}<br>@Override<br>public void Getcityname (long lat, long Lng) {<br>TODO auto-generated Method Stub<br>System.out.println ("get to the current city through Xiaomi positioning is xxxxx");<br>}<br>}<br>Interface location{<br>public void GetPosition ();<br>public void Getcityname (long Lat,long lng);<br>}</p><p><p>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, xiaomilocation 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.</p></p><p><p>Factory mode is widely used, such as the Bitmapfactory class commonly used in Android bitmap, to create bitmap objects, often using static factory METHODS.</p></p><p><p></p></p><p><p><strong>Single-case mode:</strong></p></p><p><p>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.</p></p><p><p>Let's take an example, the boring code.</p></p><p><p>public class<br>public static Hostel key;<br>public static void main (string[] Args) {<br>Room=getkey ();<br>Room.opendoor ();<br>Room1=getkey ();<br>Room1.opendoor ();<br>}<br>public static guest GetKey () {<br>If (key==null) {<br>Key=new ();<br>}<br>Return key;<br>}<br>public void Opendoor () {<br>System.out.println ("i opened the door ...");<br>}<br>}</p></p><p><p><span style="line-height: 1.5;">Look at the example above, is it similar to the example I gave to the hotel? You don't care how many times you take the key, you take the same room key, will not send you a hand, so do, save the hotel time, 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.</span></p></p><p><p></p></p><p><p><strong>Viewer Mode:</strong></p></p><p><p>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.</p></p><p><p>To experience a piece of code</p></p><p>Import java.util.ArrayList;<br>Import java.util.List;<br> <br> <br>public class Myoberver {<br>public static void main (string[] Args) {<br>American american=new American ();<br>Chinese chinese=new Chinese ();<br>iphone iphone=new iphone ();<br>System.out.println ("an American registered to buy");<br>Iphone.register (american);<br>System.out.println ("a Chinese registered to buy");<br>Iphone.register (chinese);<br>try {<br>SYSTEM.OUT.PRINTLN ("after 6 months of long waiting ...");<br>Thread.Sleep (2000);<br>} catch (interruptedexception E) {<br>TODO auto-generated Catch block<br>E.printstacktrace ();<br>}<br>Iphone.notifys ();<br>}<br>}<br>/** Viewer */<br>Class iphone{<br>Private list<fensi> list=new arraylist<fensi> ();<br>public void Register (fensi N) {<br>List.add (n);<br>System.out.println ("another Apple has been booked, now there are:" +list.size () + "personal booking ...");<br>}<br>public void NOTIFYs () {<br>System.out.println ("IPHONE 6 is now on High-profile sale ...");<br>For (fensi N:list) {<br>N.receive ();<br>}<br>}<br>}<br>Class American implements fensi{<br>@Override<br>public void Receive () {<br>TODO auto-generated Method Stub<br>System.out.println ("the Americans shout: hum, a little expensive ...");<br>}<br>}<br>Class Chinese implements fensi{<br>@Override<br>public void Receive () {<br>TODO auto-generated Method Stub<br>System.out.println ("chinese: I finally bought, happy dead ...");<br>}<br>}<br>Interface fensi{<br>public void Receive ();<br>}</p><p><p>Post-run output Results:</p></p><p><p>An American registered to buy</p></p><p><p>Another Apple has been booked, now total: 1 people booked ...</p></p><p><p>A Chinese registered to buy</p></p><p><p>Another Apple has been booked, now Total: 2 people booked ...</p></p><p><p>After 6 months of long wait ...</p></p><p><p>IPHONE 6 is now on High-profile sale ...</p></p><p><p>The Americans shouted: hmm, a little expensive ....</p></p><p><p>Chinese: I finally bought, happy dead ....</p></p><p><p></p></p><p><p>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.</p></p><p><p></p></p><p><p>Proxy mode:</p></p><p><p>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.</p></p><p><p>The same place is:</p></p><p><p>1, all need to submit the Plaintiff's information, such as name, age, cause of the matter, want to achieve the Purpose.</p></p><p><p>2, all need to go through the forensic investigation, Court debate and other Processes.</p></p><p><p>3. Finally get the result of the Trial.</p></p><p><p>Different places are:</p></p><p><p>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.</p></p><p><p>2, grasp the Greater.</p></p><p><p></p></p><p><p>From the above example, we note that the proxy pattern has several key points.</p></p><p><p>1, the role of the agent (xiao Li)</p></p><p><p>2. Acting Role (lawyer)</p></p><p><p>3, the agreement (whether agents and agents who do, all need to do things, abstract out is the Agreement)</p></p><p><p></p></p><p><p>Here's an example:</p></p><p>public class Proxy {<br>public static void main (string[] Args) {<br>Employer Employer=new Employer ();<br>System.out.println ("i can't stand it, I want to sue the boss");<br>System.out.println ("get A lawyer to solve it ...");<br>Protocol lawyerproxy=new Lawyerproxy (employer);<br>Lawyerproxy.register ("blossoming flowers");<br>Lawyerproxy.dosomething ();<br>Lawyerproxy.notifys ();<br>}<br>}<br>Interface protocol{<br>Registration information<br>public void Register (String name);<br>Investigate the case and litigate<br>public void DoSomething ();<br>The lawsuit is complete, inform the employer<br>public void NOTIFYs ();<br>}<br>Lawyer Class<br>Class Lawyerproxy implements protocol{<br>Private employer employer;<br>Public Lawyerproxy (employer Employer) {<br>this.employer=employer;<br>}<br>@Override<br>public void Register (String Name) {<br>TODO auto-generated Method Stub<br>This.employer.register (name);<br>}<br> <br>public void Collectinfo () {<br>System.out.println ("as A lawyer, I need to organize and investigate according to the information provided by the employer, write the written words to the court and provide evidence." ");<br>}<br>@Override<br>public void DoSomething () {<br>TODO auto-generated Method Stub<br>Collectinfo ();<br>This.employer.dosomething ();<br>Finish ();<br>}<br>public void Finish () {<br>System.out.println ("this lawsuit has been finished ...");; ");<br> <br>}<br>@Override<br>public void NOTIFYs () {<br>TODO auto-generated Method Stub<br>This.employer.notifys ();<br>}<br>}<br>Employer class<br>Class Employer Implements Protocol{<br>String name=null;<br>@Override<br>public void Register (String Name) {<br>TODO auto-generated Method Stub<br>this.name=name;<br>}<br> <br>@Override<br>public void DoSomething () {<br>TODO auto-generated Method Stub<br>System.out.println ("i am" "+this.name+" to sue B total, He keeps me working overtime every day, there is no overtime pay. ");<br>}<br> <br>@Override<br>public void NOTIFYs () {<br>TODO auto-generated Method Stub<br>System.out.println ("the court ruled that the lawsuit won, B always need to compensate 100,000 yuan for spiritual compensation." ");<br>}<br> <br>}</p><p><p></p></p><p><p>After running, print as Follows:</p></p><p><p>I'm going to sue the boss for a lawsuit.</p></p><p><p>Ask a lawyer to solve it ...</p></p><p><p>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.</p></p><p><p>I am ' blossoming flower ' to sue B total, He keeps me working overtime every day, there is no overtime pay.</p></p><p><p>This lawsuit has been finished ...... .....</p></p><p><p>The court ruled that the lawsuit won, B always need to compensate 100,000 yuan spiritual compensation fee.</p></p><p><p>Code description:</p></p><p><p>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.</p></p><p><p>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.</p></p><p><p>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.</p></p><p><p>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?</p></p><p>public class Proxy {<br>public static void main (string[] Args) {<br>Employer Employer=new Employer ();<br>System.out.println ("i can't stand it, I want to sue the boss");<br>System.out.println ("get A lawyer to solve it ...");<br>Protocol lawyerproxy=new lawyerproxy ("blossoming bloom");<br>Lawyerproxy.dosomething ();<br>Lawyerproxy.notifys ();<br>}<br>}<br>Interface protocol{<br>Registration information<br>public void Register (String name);<br>Investigate the case and litigate<br>public void DoSomething ();<br>The lawsuit is complete, inform the employer<br>public void NOTIFYs ();<br>}<br>Lawyer Class<br>Class Lawyerproxy implements protocol{<br>Private employer employer;<br>Public Lawyerproxy (String Name) {<br>If (name==null) {<br>System.out.println ("who Sued?") You kidding me? ");<br>Return<br>}<br>If (employer==null) employer=new employer ();<br>Register (name);<br>}<br>@Override<br>public void Register (String Name) {<br>TODO auto-generated Method Stub<br>This.employer.register (name);<br>}<br> <br>public void Collectinfo () {<br>System.out.println ("as A lawyer, I need to organize and investigate according to the information provided by the employer, write the written words to the court and provide evidence." ");<br>}<br>@Override<br>public void DoSomething () {<br>TODO auto-generated Method Stub<br>Collectinfo ();<br>This.employer.dosomething ();<br>Finish ();<br>}<br>public void Finish () {<br>System.out.println ("this lawsuit has been finished ...");; ");<br> <br>}<br>@Override<br>public void NOTIFYs () {<br>TODO auto-generated Method Stub<br>This.employer.notifys ();<br>}<br>}<br>Employer class<br>Class Employer Implements Protocol{<br>String name=null;<br>@Override<br>public void Register (String Name) {<br>TODO auto-generated Method Stub<br>this.name=name;<br>}<br> <br>@Override<br>public void DoSomething () {<br>TODO auto-generated Method Stub<br>System.out.println ("i am" "+this.name+" to sue B total, He keeps me working overtime every day, there is no overtime pay. ");<br>}<br> <br>@Override<br>public void NOTIFYs () {<br>TODO auto-generated Method Stub<br>System.out.println ("the court ruled that the lawsuit won, B always need to compensate 100,000 yuan for spiritual compensation." ");<br>}<br> <br>}</p><p><p></p></p><p><p>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.</p></p><p><p></p></p><p><p>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.</p></p><p><p></p></p><p><p>An explanation of common Android design patterns</p></p></span>

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.