Android application to design patterns

In fact, the average programmer to write business code, design patterns does not take much. Write easy to understand and maintain the code relatively more important.

 

I. Introduction

What is that design patterns?

Many people, including me, have fans caught in the 23 design patterns, design patterns acquaintance, praise their exquisite, like a sprouting of new niche rivers and lakes, accidentally fell into the cave, click on the assembly of the Megatron rivers and lakes of "seven kinds of weapons." ...... then began chopping sword with longevity, jasper sliced ​​melon "happy life", not only the simple things made a huge complex.

Back to the design mode, is that under the guidance of the principles of object-oriented principles of these illusory "Heart", those seniors who left the Great God "moves" or "routine" only. But the moves and routines are not winning, it only provides a great God is closer to us and so white, miscellaneous ways of understanding it, by imitating over many years to reflect to comprehend and understand the nature of "Heart" and exquisite, which explain why using the same moves, the great God who always Yijizhiming, and we are always lost in a niche.

Continue to practice "to reconstruct mode", through the practical application of practical guidelines and practices, deduction moves and routines that help us digest these two methods, combined with each other, and ultimately realize that behind every appearance of truth, to no stroke victory have strokes, vegetation Takeishi can serve as a sword, heart random walk, human heart action realm.

Second, the design mode

Android source code involves a lot of design patterns.

2.1 builder mode

Builder model is the most obvious sign is Build class, and in the most commonly used is the Android Dialog build, build is the standard mode Notification of builders. The builder pattern is better understood, if the structure of a class requires a lot of parameters, and these parameters are not necessary, so in this case more suitable Builder.

Such as building a AlertDialog, title, content, Cancel button, OK button, the neutral button, you may only need to set a few properties can be alone.

2.2 singleton

Singleton often used in Android development, but the form of expression may not be the same. ActivityManager services to other systems, is achieved by way of a single embodiment of a static block when it is first loaded class files generated singleton object, and then stored in the Cache, then are used directly from the Cache. Of course, there are more obvious examples, such as internal AccessibilityManager themselves to ensure that a single case, using the getInstance Gets the singleton object.

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 single cases, such as Application, by default there is only one instance of a process, but it can not be regarded Application singleton, because its constructor is not private, you can generate multiple Application examples, but to no avail, you are not bound by relevant information attach (), no context.

public Application() {
    super(null);
}

  

Using a single scene is also very simple embodiment, only APP is a need for the presence of a class instance or class initialization operation of the resource consuming. In many open source framework, we only need to complete the work of an object, such as a variety of network frame and image loading library.

In addition, because many implementations of a single case of such lazy man, hungry man type, static inner classes, double check the lock, enumerations, etc., so be aware of the main features of each implementation and usage scenarios.

2.3 prototype model

Prototype model used is not much in development, but reflected in the source code. Intent to introduce the prototype mode, the interface is done by implementing the Cloneable

public class Intent implements Parcelable, Cloneable {
    @Override
    public Object clone() {
        return new Intent(this);
    }
}

  

In fact, this view, then, what you want to get a quicker same attributes object, then you can use the prototype model, such as here on a Intent to acquire objects, properties, and the same clone of Intent to be inside, but a combination of both no association, it may be used alone.

In addition to implementing the Cloneable interface, you can define your own a method to get an object. PhoneLayoutInflater as an example to introduce.

PhoneLayoutInflater is LayoutInflater subclass, if we get LayoutInflate in Activity in the words, by the following method:

@Override 
public Object getSystemService(String name) {
    if (LAYOUT_INFLATER_SERVICE.equals(name)) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
        }
        return mInflater;
    }
    return getBaseContext().getSystemService(name);
}

  

You can see, if it is null, it will call cloneInContext (), this method is an abstract method in LayoutInflate, embodied in the PhoneLayoutInflater

public LayoutInflater cloneInContext(Context newContext) {
    return new PhoneLayoutInflater(this, newContext);
}

  

You can see, this is a prototype model, so we do not get too tangled to form, more importantly, understand the benefits of doing so.

In addition to the source can be seen in the prototype model, it can also be seen in the open source framework, such as exists in respect OkHttpClient following method

/** Returns a shallow copy of this OkHttpClient. */
@Override
public OkHttpClient clone() {
    return new OkHttpClient(this);
}

  

It can be seen exactly achieve and foregoing, an object is new returned because OkHttpClient construction process more complex, a number of parameters, so in this way to generate a new object directly, low cost, and can retain the previous object parameter settings.

2.4 Factory Method

Factory method for a pattern view of a novelty, is your Activity.onCreate () method can be seen as the factory mode, generating a different View interface objects filled.

Static factory method in Android should be relatively obvious example is the BitmapFactory, you can obtain a Bitmap object from different sources through a variety of decodeXXX ().

2.5 Strategy Pattern

Strategy mode is equivalent to a player, what you drive a plug dishes, you can release what movie.

The essence of the strategy pattern is that you pass a class, you can do it later processing in accordance with the realization of this class. In animation, for example, a different set of interpolation object, you can get different curves; to return the value resolution, for example, what the incoming parser, binary data can be converted into what data format, such as String, json, XML.

2.6 Chain of Responsibility pattern

For example, the chain of responsibility pattern selected very representative, it is touch mechanism of Android, this view allows us to understand from another dimension in the Android touch event delivery.

2.7 Observer pattern

Android in the observer model should be used very frequently as a model, and for this pattern of usage scenarios on the word: when you want an object changes immediately notified.

The observer pattern using a ListView Adapter as an example, before I knew Adapter belong adapter mode, do not know the figure of the observer pattern here, learn.

Android inside a variety of listeners, also belong to the observer pattern, such as touch, tap, buttons, etc., ContentProvider and radio receivers also figure observer mode, it can be said to be everywhere.

In addition, many third-party observer pattern-based framework is very large, such as EventBus, RxJava etc., we are deeply observer mode of use.

2.8 Template Method Pattern

I had less contact this mode, but after understanding, you will find this model is very simple. The method of using a template pattern word scenarios are: the process is determined, the specific implementation details completed by subclasses.

Here we must look at the "process" keyword, simply take an abstract class, are in line with "the specific implementation details completed by subclasses" requirements, the key lies in whether there is flow, with the process, called template method pattern, no process , it is to implement an abstract class.

This mode is used AsyncTask, executed between the various methods in line with the process, concrete realization done by us, very classic.

In addition to Android template method pattern inside, in other open source projects, there are also using this model.

2.9 Proxy Mode and Decorator

The reason why these two together, said, because of these two models like, so here briefly the differences between them, the two main points.

Decorator attention to dynamically add a method on an object, and proxy mode to focus on controlling access to the object

Proxy mode, the agent class can hide an object to its customer specific information. Therefore, when using the agency model, we often create an instance of an object in a proxy class. And when we use the decorator pattern, the usual practice is to the original object as a parameter to the constructor decorator

These two statements may not be easy to understand, it does not matter, look at the following example.

Proxy mode will hold the instance of the proxy object, and this instance is generally used as member variables directly present in the proxy class that no additional assignment.

For example WindowManagerImpl is a proxy class, although looking like the name, but it is WindowManagerGlobal proxy object. From the following code can be seen.

public final class WindowManagerImpl implements WindowManager {
    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
    private final Display mDisplay;
    private final Window 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
    public Display getDefaultDisplay() {
        return mDisplay;
    }
}

  

As can be seen from the above code, most methods WindowManagerImpl are achieved by WindowManagerGlobal, no additional objects and WindowManagerGlobal assignment, it is present in the WindowManagerImpl. In addition, there are in fact plenty of ways WindowManagerGlobal, but after WindowManagerImpl by proxy, are not exposed to developers is transparent.

Let us look at the decorator pattern. Decorative object control mode is not the access, but the extensions, compared to the base class inherits extension, the decorator pattern more flexible.

The book is based on Context and its packaging ContextWrapper explain, but also very typical, posted some code to illustrate the form of the decorator pattern.

public class ContextWrapper extends Context {
    Context mBase;

    public ContextWrapper(Context base) {
        mBase = base;
    }
}

  

But there is a problem, that is, ContextWrapper, the realization of all the methods are achieved through mBase, formally on the number, saying good extensions of it?

Extension is in fact ContextWrapper subclass ContextThemeWrapper inside.

In ContextWrapper inside, access to system services is done directly through mBase

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

  

But in ContextThemeWrapper inside, this method has been rewritten to complete the function expansion

@Override 
public Object getSystemService(String name) {
    if (LAYOUT_INFLATER_SERVICE.equals(name)) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
        }
        return mInflater;
    }
    return getBaseContext().getSystemService(name);
}

  

Of course, if there is no extensions will not be the decorator pattern yet? In fact, the design mode always been "eyes of the beholder, the wise see wisdom" thing.

Third, the summary

In fact, Android design patterns do exist everywhere, not a lack of design patterns, but the lack of attention to. Of course, the proposed design pattern to solve a specific problem, when we encounter a similar problem, you can think and solve problems from the perspective of design patterns.

Design pattern is not a panacea, it is actually neutral, neither good nor bad.

about me

For more information you can click on me  , and very much like to share with everyone, and common progress

Guess you like

Origin www.cnblogs.com/1157760522ch/p/11593314.html