"Android Source design mode Analysis" Reading notes--android you should know the design patterns

Source: Internet
Author: User

Intermittent, "Android source code design mode analysis" also read, the book mentions a lot of design patterns, but some in the development of the odds are very small, so can not master nor too much influence.

I think the maximum value of this book is two points, one is from the point of view of design mode to understand the Android source code, combined with the daily development of common classes, the understanding of design patterns will be more profound; another advantage is to understand the common patterns, and then look at other people write code, it is easier to understand the code ideas. Here are my reading notes and some thinking, and the design pattern only collates the parts I think are important.

Builder mode

The most obvious sign of builder mode is the build class, and the most common use of Android is dialog, and the notification build is the standard builder model.

The builder pattern is well understood, and if a class's construction requires a lot of parameters, and these parameters are not all necessary, then this is the case for builder.

For example, to build a alertdialog, title, Content, Cancel button, OK button, neutral button, you may only need to set a few properties alone, and in my Okhttpplus project, the construction of an HTTP request is the same, it is possible that you only need to set the URL, It is possible to add request parameters, Http headers, and so on, this time the builder mode is also more appropriate.

Single-Case mode

A single case is often used in Android development, but the form may not be the same.

In the case of system services such as Activitymanager, a singleton is implemented in the form of a static block of code, when the class file is first loaded, a singleton object is generated, then saved in the cache, and then used directly from the cache.

class ContextImpl extends Context {    static {        new ServiceFetcher() {                public Object createService(ContextImpl ctx) {                    returnnew ActivityManager(ctx.getOuterContext(),       ctx.mMainThread.getHandler());                }});    }}

There are, of course, more obvious examples, such as Accessibilitymanager internal guarantees of singleton, using getinstance to obtain singleton objects.

 public   Static  Accessibilitymanager getinstance  (Context context) {synchronized  (sinstancesync) {if  (sinstance = = null ) {...                IBinder IBinder = Servicemanager.getservice (Context.accessibility_service); Iaccessibilitymanager Service = IBinder = = null ?                null : IAccessibilityManager.Stub.asInterface (IBinder);            Sinstance = new  accessibilitymanager (context, service, userId);    }} return  sinstance; }

In addition, there are some pseudo-singleton, such as application, by default there is only one instance in a process, but application is not a singleton, because its construction method is not private, you can generate multiple application instances, but it is useless, You did not bind information through attach (), there is no contextual context.

publicApplication() {        super(null);    }

The use of a single case is also very simple, that is, an app only needs to have a class instance of the case, or the class initialization operation is more resource-intensive situation. In many open source frameworks, we need only one object to do the work, such as various network frameworks and image loading libraries.

In addition, because there are a lot of implementations of Singleton, such as lazy, a hungry man, static inner class, double lock check, enumeration, etc., it is important to understand the main features and usage scenarios of each implementation mode.

Prototype mode

Prototype model in the development of the use of not much, but in the source code is reflected.

In the book, intent introduces the prototype pattern, which is done by implementing the Cloneable interface.

publicclass Intent implements Parcelable, Cloneable {    @Override        publicclone() {         returnnew Intent(this);        }    }

In fact, in this case, the prototype model is also better understood, is that you want to get a faster object of the same property, then you can use the prototype mode, such as here to get a intent object, intent inside the property is the same as the clone, but the two are not associated, can be used alone.

In addition to implementing the Cloneable interface, you can completely define a method to get an object. I am here to introduce Phonelayoutinflater as an example.

Phonelayoutinflater is a subclass of Layoutinflater, and if we get layoutinflate in activity, it's done by the following method

publicgetSystemService(String name) {        if (LAYOUT_INFLATER_SERVICE.equals(name)) {            ifnull) {                mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);            }            return mInflater;        }        return getBaseContext().getSystemService(name);    }

As you can see, if NULL, Cloneincontext () is called, which is an abstract method in Layoutinflate, implemented in Phonelayoutinflater

  publiccloneInContext(Context newContext) {        returnnew PhoneLayoutInflater(this, newContext);    }

As you can see, this is also a prototype pattern, so let's not get too tangled up in the form and, more importantly, understand the benefits of doing so.

In addition to the source code can be seen in the prototype model, in the open source framework can also be seen, such as okhttpclient in the following methods exist

/** Returns a shallow copy of this OkHttpClient. */  @Overridepublicclone() {    returnnew OkHttpClient(this);  }

As you can see, the implementation is exactly the same as the previous one, and new has an object return, because the okhttpclient construction process is complex and has many parameters, so it is very inexpensive to generate the new object directly in this way, and it retains the parameter settings of the previous object.

Factory method Mode

A novel view of the factory approach model is that activity.oncreate () can be seen as a factory method pattern to generate different view object fill interfaces.

But I disagree with this statement for two reasons: first, this form is not in line with the factory method, no abstraction, no implementation, does not conform to the general format, is not a static method, not as a static factory method, the second is not to generate objects as a result, that is, not a return view to generate objects, Only the properties are set by Setcontentview (). It's like setting a background color for an activity. Of course, design patterns this thing a person has a person's opinion.

Static factory methods in Android is the obvious example should be bitmapfactory, through a variety of decodexxx () can be obtained from different channels bitmap objects, here no longer repeat.

Policy mode

In the book The Strategy mode is very good, combined with the animation of the Interpolator usage, we can well understand the form and usage of the strategy pattern.

In my opinion, the strategy model is the equivalent of a DVD player, you can put in the inside of what dish, will be able to release what movie.

Similarly, in the Okhttpplus package, I used the policy mode in order to parse the return value of the network. Of course, I write code when I do not know the strategy mode, is finished after the sudden thought, this is the strategy mode Ah!

The essence of the strategy pattern is that you pass in a class, and the subsequent processing can follow the implementation of that class. Taking animation as an example, the different interpolation objects can be used to get different curves, and in the case of return value resolution, the parser can be used to convert binary data into what format data, such as String, Json, XML.

Responsibility chain Model

The book's example of the choice of chain of responsibility is that Android's touch mechanism, which allows me to understand the touch event delivery in Android from another dimension.

I mentioned this pattern here, and do not want to say too much, but simply recommend you read this chapter of the content, I believe you will also have a harvest.

Observer pattern

The observer pattern in Android should be a very frequent pattern, for the use of this pattern is a sentence: you want to be notified immediately when an object changes.

The introduction of the Observer pattern in the book is using the adapter of the ListView as an example, I know that adapter belongs to the adapter mode, I do not know that there are observer pattern figure, learned.

Android's various listeners, also belong to the Observer mode, such as touch, click, button, etc., ContentProvider and broadcast receiver also has the observer pattern figure, can be said to be everywhere.

In addition, there are many third-party frameworks based on the observer pattern are also very many, such as Eventbus, Rxjava and so on, are in-depth use of the observer pattern, interested students can study.

Template method Mode

I've seen less of this pattern before, but after understanding it, it's easy to see the pattern.

I think that the use of the template method pattern is also a sentence: process determination, the implementation of the details of sub-class completion.

Here to pay attention to the "process" this keyword, casually take an abstract class, all conform to the "specific implementation details sub-class complete" requirements, the key lies in whether there is a process, there is a process, called template method mode, no process, is the implementation of abstract class.

The book says that this pattern is asynctask, the execution of each method conforms to the process, the concrete implementation is done by us, very classic.

Another aspect, activity's life cycle method can be regarded as template method pattern, each life cycle method is sequential, concrete implementation we can rewrite, is not match with previous request? For this understanding, you can refer to my article: Understanding the Activity life cycle.

In addition to the template method model in Android, there is also the use of this pattern in other open source projects. For example, Yang's Okhttp-utils project is a typical implementation of the template method pattern. The process of splitting an HTTP request into several parts, such as obtaining a URL, getting a request header, stitching request information, and so on, is a sequence of steps that can be done.

Proxy mode and Adorner mode

The reason to put these two together, because the two models are very similar, so here is a brief introduction of the difference between them, mainly two points.

    1. Adorner mode focuses on dynamically adding methods on an object, while the proxy mode focuses on controlling access to objects
    2. Proxy mode, the proxy class can hide specific information about an object from its customers. Therefore, when using proxy mode, we often create an instance of an object in a proxy class. And when we use adorner mode, it's common practice to pass the original object as a parameter to the decorator's constructor

These two words may not be well understood, it's okay, here's an example.

The proxy mode holds an instance of the Proxied object, which is typically present as a member variable directly in the proxy class, i.e. no additional assignment is required.

For example, Windowmanagerimpl is a proxy class, although the name does not look like, but it is the agent of the Windowmanagerglobal object. As you can see from the code below.

 Public Final  class Windowmanagerimpl implements WindowManager {    Private FinalWindowmanagerglobal Mglobal = Windowmanagerglobal.getinstance ();Private FinalDisplay Mdisplay;Private FinalWindow Mparentwindow; ......@Override     Public void AddView(View view, Viewgroup.layoutparams params)    {Mglobal.addview (view, params, mdisplay, Mparentwindow); }@Override     Public void Updateviewlayout(View view, Viewgroup.layoutparams params)    {mglobal.updateviewlayout (view, params); }@Override     Public void Removeview(View view) {Mglobal.removeview (view,false); }@Override     Public void removeviewimmediate(View view) {Mglobal.removeview (view,true); }@Override     PublicDisplayGetdefaultdisplay() {returnMdisplay; }}

As you can see from the code above, most of the Windowmanagerimpl methods are implemented through Windowmanagerglobal, and Windowmanagerglobal objects do not require additional assignment. exists in the Windowmanagerimpl. In addition, Windowmanagerglobal in fact there are a number of methods, but through the Windowmanagerimpl agent, have not been exposed to the developer is transparent.

Let's look at the adorner mode again. Adorner mode is not intended to control access, but rather extends functionality, and uses adorner mode more flexibly than inheriting base classes to extend functionality.

The book is in the context and its packaging class Contextwrapper explained, but also very typical, I do not repeat here, put some code to illustrate the form of the adorner pattern.

publicclass ContextWrapper extends Context {    Context mBase;    publicContextWrapper(Context base) {        mBase = base;    }}

But there is also a problem, that is in the contextwrapper, all the implementation of the method is through the mbase to achieve, the form is on the number, the extension function?

The function extension is actually in the Contextwrapper subclass Contextthemewrapper inside.

In Contextwrapper, access to system services is done directly through Mbase.

@Override    publicgetSystemService(String name) {        return mBase.getSystemService(name);    }

But in the Contextthemewrapper, the method was rewritten to complete the function extension

publicgetSystemService(String name) {        if (LAYOUT_INFLATER_SERVICE.equals(name)) {            ifnull) {                mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);            }            return mInflater;        }        return getBaseContext().getSystemService(name);    }

Of course, wouldn't it be an adorner mode if there was no feature extension? In fact, the design pattern is the "benevolent See" thing, as long as you can understand the meaning of the good.

Appearance mode

The appearance mode may see less, but in fact inadvertently you use.

Here in my open source project Klog, in the beginning to write this class, only klog this class, complete the basic log printing function, and then add the JSON parsing, XML parsing, log information storage and other functions, this time a class is not very suitable, so I put JSON, XML, file operation-related code is extracted into separate classes, such as JSON-printed code

 Public classJsonlog { Public Static void Printjson(string tag, string msg, String headstring) {String message;Try{if(Msg.startswith ("{") {Jsonobject Jsonobject =NewJsonobject (msg);            Message = jsonobject.tostring (klog.json_indent); }Else if(Msg.startswith ("[") {Jsonarray Jsonarray =NewJsonarray (msg);            Message = jsonarray.tostring (klog.json_indent); }Else{message = MSG; }        }Catch(Jsonexception e)        {message = MSG; } util.printline (Tag,true);        Message = headstring + klog.line_separator + message; String[] lines = Message.split (klog.line_separator); for(String line:lines) {LOG.D (tag,"║"+ line); } util.printline (Tag,false); }}

The code is simple, just a method, but when used, it is used regardless of which format is printed.

//普通打印 KLog.//JSON格式打印 KLog.//XML格式打印 KLog.xml(XML);

As can be seen, although the function is different, but all through klog this class is encapsulated, the user only know with Klog this class can complete all requirements can, completely do not need to know that the code implementation is a few classes to complete.

In fact, within Klog, there are multiple classes that work together to complete the printing function.

private staticvoidPrintlog (int type,StringTAGSTR,Object... objects) {if(!is_show_log) {return; }String[] contents = Wrappercontent (Tagstr, objects);StringTag = contents[0];Stringmsg = contents[1];Stringheadstring = contents[2];Switch(type) { CaseV: CaseD: CaseI: CaseW: CaseE: CaseA:baselog.printdefault (type, tag, headstring + msg); Break; Case JSON: Jsonlog.printjson (Tag, MSG, headstring); Break; CaseXML:XMLLOG.PRINTXML (tag, MSG, headstring); Break; }    }

But through the appearance mode, these details are hidden from the user, so if later I want to change the JSON parsing method, the user's code does not need any change, this is also the advantage of this design pattern.

Summarize

Nagging, finally is the introduction of these kinds of design patterns, after reading this article, you should be found in fact, Android design patterns are everywhere, not lack of design patterns, but the lack of a pair of discovered eyes.

Of course, the design pattern of the proposed is to solve specific problems, when we encounter similar problems, can be from the perspective of design patterns to think and solve problems, this should be my biggest harvest.

About Me

The lake is called "the elder brother", the Android developer, likes the technology to share, loves the open source.

    • My csdn Blog: http://blog.csdn.net/zhaokaiqiang1992
    • My Weibo: Naked Ben's brother, every day will not regularly share high-quality blog, welcome attention
    • Public account: kaizige1992

"Android Source design mode Analysis" Reading notes--android you should know the 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.