23 Design Patterns for Android applications

Source: Internet
Author: User

All rivers and lakes encounter, are doomed to meet----"upstream cold", just think the copy is good, it is used. Ha ha!

I. Design principles:

Single responsibility Principle (SRP): Any one object should give only one separate responsibility ("low-coupling, cohesion poly")
Richter replacement Principle (LSP): Can be substituted with subclasses wherever any parent class appears
Dependency Injection principle (DIP): Depends on abstraction rather than on concrete implementation (this principle is the basis of the open and close principle)
Interface separation principle (ISP): should not force their client programs to rely on methods they do not need
Dimitri Principle (LOD): An object should know as little as possible about other objects, meaning that it reduces the coupling between the various objects.
Open/Close principle (OCP): A pair of objects is opened to the extension, and the modification is closed.

Two. 23 Design mode

1. Factory mode (Factory pattern): in the factory model, the customer class and the factory to be separate, the consumer needs the product at any time only need to request to the factory, the consumer can accept the new product without modification. The disadvantage is: the current product modification is the factory also need to modify.

2. Construction Mode (builder pattern): The product's internal appearance and product generation process is separated, so that a construction process to produce a different representation of the product, construction mode so that the internal appearance of the product can be independent changes, customers do not need to know the internal details of the product. The construction model can be used to enforce a step construction process.

Alertdialog.builder Builder =NewAlertdialog.builder ( This); Builder.settitle (""). SetIcon (R.drawable.ic_launcher_foreground). Setview (R.layout.activity_main) . Setonkeylistener (NewDialoginterface.onkeylistener () {@Override Public BooleanOnKey (Dialoginterface Dialoginterface,intI, KeyEvent keyevent) {                        return false; }}). Setoncancellistener (NewDialoginterface.oncancellistener () {@Override Public voidOnCancel (Dialoginterface dialoginterface) {}}) . Create (). Show ();
View Code

3. Factory Method Mode (abstract Factory pattern): in the factory method mode, the core factory class is no longer responsible for the creation of all products, but rather the specific creation work to subclass processing, as an abstract role, only responsible for the specific factory must implement the interface Without touching the instanced details of a particular product.

4. prototype Model mode (Prototype pattern): The prototype model is a prototype object that specifies the type of object to be created, and can create more objects with the method of copying the object, and the prototype model allows the product class to be dynamically increased or decreased. The disadvantage is that each class must be equipped with a clone method.

5. Singleton mode (Singleton pattern): ensures that a class has only one instance, and instantiates itself and provides this instance singleton pattern to the entire system.

-A Hungry man type single case

public class Singleton {
Private Singleton () {}
private static Singleton instance = new Singleton ();
public static Singleton getinstance () {
return instance;
}
}

-Lazy Type Single case

/**
* Singleton Helper class for lazily initialization.
*
* Modeled after Frameworks/base/include/utils/singleton.h
*
* @hide
*/
Public abstract class Singleton<t> {
Private T minstance;

Protected abstract T Create ();

Public final T get () {
Synchronized (this) {
if (minstance = = null) {
Minstance = Create ();
}
return minstance;
}
}
}

A hungry man mode is the operation of the system, in the class when the initialization of operations, external objects do not need to make any judgment can be used directly, from the efficiency is better than the lazy mode. However, the lazy loading technique is compared with the idle mode, regardless of the system's use of this instance, The memory will be created at the very beginning. In the opposite direction, the A hungry man is space-changing time.

6. Adapter Mode (Adapter pattern): change the interface of my class to another interface expected by the client.

Adapter.java Android8.0 Source

/*** The adapter object acts as a bridge between Adapterview and the view presentation data. Provides access to data. * Also responsible for data set control for each of the Android.view.View controls. * @seeAndroid.widget.ArrayAdapter *@seeAndroid.widget.CursorAdapter *@seeAndroid.widget.SimpleCursorAdapter*/ Public InterfaceAdapter {/*** Register an observer-called when changes happen to the data used by this adapter. * When the data released by this adapter is changed, register an observer *@paramObserver the object that gets notified when the data set changes. * @paramObserver the object to be notified when the data set has changed*/    voidRegisterdatasetobserver (Datasetobserver observer); /*** Unregister an observer that have previously been registered with this * adapter via {@link#registerDataSetObserver}. * This method is written off by the Observer, *@paramObserver the object to unregister. * @paramObserver The observer who needs to be unregistered*/    voidUnregisterdatasetobserver (Datasetobserver observer); /*** How many items is in the data set represented by this Adapter. * Adapter Data Set Size *@returnCount of items. * @returnreturn Data set size*/    intGetCount (); /*** Get The data item associated with the specified position in the data set. * Returns the data item object for the dataset's corresponding index (position) *@paramposition position of the item whose data we want within the adapter ' s * Data set. * @returnThe data at the specified position. */Object GetItem (intposition); /*** Get The row ID associated with the specified position in the list. * Returns the data item ID of the data set corresponding index (position) *@paramposition the position of the item within the adapter ' s data set whose row ID we want. * @returnThe ID of the item at the specified position. */    LongGetitemid (intposition); /*** Indicates whether the item IDs is stable across changes to the * underlying data.     * True if the same ID always refers to the same object. * @returnTrue If the same ID always refers to the same object. */    BooleanHasstableids (); /*** Get A View that displays the data on the specified position in the data set. can either * Create a View manually or inflate it from an XML layout file. When the view is inflated, the * parent view (GridView, ListView ...) would apply default layout parameters unless U SE * {@linkandroid.view.layoutinflater#inflate (int, Android.view.ViewGroup, Boolean)} * To specify a root view and to Preven     T attachment to the root. * Returns the view specified by the corresponding index (position) in the dataset.     You can also create a view or inflate through an XML layout. * If the view is obtained through inflate,@paramThe parent can be a control such as a GridView or a ListView. * Unless you use {@linkandroid.view.layoutinflater#inflate (int, Android.view.ViewGroup, Boolean)} specifies the root view and prevents attachment, otherwise the default layout parameters are used. * @paramposition the position of the item within the adapter ' s data set of the item whose view * we want. * @paramposition we want to return the view that corresponds to the dataset index (position) *@paramConvertview The old view to reuse, if possible. Note:you should check the This view * is non-null and of a appropriate type before using.     If It is not possible to convert * This view to display of the correct data, this method can create a new view. * Heterogeneous lists can specify their number of view types, so ' this view is * always of the RI Ght type (see {@link#getViewTypeCount ()} and * {@link#getItemViewType (int)}). * @paramConvertview If you can, reuse the old view. Note: You need to check that the view is not null and is of the appropriate type.     If you cannot reuse it, you can create a view. * @paramParent The parent that this view would eventually be attached to *@paramParent Root View *@returnA View corresponding to the data at the specified position.     * Returns the view that renders the data set index corresponding data item. */View GetView (intposition, View Convertview, viewgroup parent); /*** An item view type that causes the {@linkAdapterview} to ignore the item * view. For example, this can is used if the client does not want a * particular view to being given for conversion in * {@link#getView (int, View, ViewGroup)}. *      * @see#getItemViewType (int) *@see#getViewTypeCount ()*/    Static Final intIgnore_item_view_type =Adapterview.item_view_type_ignore; /*** Get The type of View that would be a created by {@link#getView} for the specified item. *      * @paramposition the position of the item within the adapter ' s data set whose view type we * want. * @returnAn integer representing the type of View. The should share the same type if one * can be converted to the other in {@link#getView}. Note:integers must is in the * range 0 to {@link#getViewTypeCount}-1. {@link#IGNORE_ITEM_VIEW_TYPE} can * also be returned. * @see#IGNORE_ITEM_VIEW_TYPE*/    intGetitemviewtype (intposition); /*** <p> * Returns The number of types of views that would be being created by * {@link#getView}. Each of the type represents a set of views that can is * converted in {@link#getView}.     If the adapter always returns the same * type of View in all items, this method should return 1. * </p> * <p> * This method would only be called when the adapter are set on the {@linkAdapterview}. * </p> * *@returnThe number of types of views that would be created by this adapter*/    intGetviewtypecount (); Static Final intNo_selection =Integer.min_value; /**      * @returntrue if this adapter doesn ' t contain any data.  This was used to determine * whether, the empty view should be displayed. A Typical implementation would return * GetCount () = = 0 but since GetCount () includes the headers and footers, special      ized * Adapters might want a different behavior. */     BooleanIsEmpty (); /*** Gets A string representation of the adapter data that can help * {@linkAndroid.service.autofill.AutofillService} autofill The view backed by the adapter. * * <p> * It should only is set (i.e., non-{@codeNULL} If the values do not represent PII * (Personally identifiable information-sensitive data such as email ad Dresses, * Credit card numbers, passwords, etc ...). For * example, it's OK to return a list of month names, and not a list of usernames. A good rule of * thumb is the If the adapter data comes from static resources, such data are not Pii-see * {@linkandroid.view.viewstructure#setdataissensitive (Boolean)} for more info. *     * @return {@codenull} By default, unless implementations override it. */    default@Nullable charsequence[] getautofilloptions () {return NULL; }}
View Code

7. Bridging mode (bridge pattern): the abstraction and implementation decoupling, so that they can change independently, that is, their strong association into a weak association, that is, the software system uses a combination/aggregation relationship rather than the inheritance relationship, so that the two can change independently.

8. Compositing mode (Composite pattern): combines objects into a tree structure to represent a "partial-whole" hierarchy, allowing users to have consistent use of individual objects and composite objects

9. Decorator Mode (Decorator pattern): The adorner mode extends the function of the object transparently to the client, is an alternative to the inheritance scheme, provides more flexibility than inheritance, and dynamically adds functionality to an object that can be dynamically revoked. Additional basic functional permutations can be added to produce very powerful features.

The façade mode (facade pattern): external communication with a subsystem must be done through a façade object, and the façade mode provides a high-level interface that makes the subsystem easier to use. Each subsystem has only one façade class, and there is only one instance of this façade class, and a single whole system can have multiple façade classes.

Flyweight Pattern: use shared objects to effectively support a large number of fine-grained objects.

Proxy pattern: creates a proxy object for an object and controls the application of the source object by the proxy object.

responsibility Chain mode (chain of responsinbleity pattern): enables multiple objects to have the opportunity to process requests, thus avoiding the coupling between the sender and receiver of the request. Connect these objects to a chain and pass the request along this chain, knowing that there are objects to handle it

Command mode (cmd pattern): encapsulates a request into an object, allowing you to parameterize the client with different requests, queue requests, or log request logs to provide undo and redo functions for the command.

Theinterpreter pattern (interpreter pattern): Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.

Iteration Sub-pattern (Iterator pattern): It provides a way to access individual elements in a container object without exposing the internal details of the object.

The Mediator pattern (mediator pattern): The Mediator pattern wraps a series of objects interacting in such a way that the objects do not have to interact with each other clearly. So that they can be loosely coupled. When the role of some objects changes, it does not immediately affect the effect of other objects. Ensure that these effects can change independently of each other. The mediator model converts many-to-many interactions into one-to-many interactions. The Mediator pattern abstracts the behavior and collaboration of objects, and separates them from the interactions of other objects on small-scale behaviors.

Memo Mode (Memento pattern): captures the internal state of an object without destroying the package, and saves the state outside the object so that the object can be restored to its original saved state.

Observer mode (Observer pattern): defines a one-to-many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and automatically updated

Status mode (state pattern): When an object is allowed to change its behavior when the state changes, the object looks like it has changed its class.

Strategy Mode (Strategy pattern): defines a set of algorithms that encapsulate each algorithm and enable them to be interchanged

Template Method Pattern:

The visitor pattern (Visitor pattern): encapsulates a number of elements that act on a data structure, and it can define new operations that act on these elements without changing the data structure


Reference:
79050044

23 Design Patterns for Android applications

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.