The adoption of design patterns in ANDROID--Create-mode

Source: Internet
Author: User



A pattern is a fixed solution that solves a problem in a situation.

All creation patterns are used as a solution for creating or instantiating objects.

1 Simple Factory mode

The simplest way to create an object is to use new to create an object, and if you create only one fixed object , you can use new to create the object.

If you want to create different types of objects based on different scenarios, you may need to take different approaches and introduce different patterns and summaries.

such as the ANDROID Media frame in order to achieve the playback of different media sources, you need to implement a variety of player objects, and may need to be based on the support of the increase in the type of media to continue to add player objects.

 Sp<mediaplayerbase> p;            Switch (playertype) {case SONIVOX_PLAYER:ALOGV ("Create MidiFile");            p = new MidiFile ();        Break            Case STAGEFRIGHT_PLAYER:ALOGV ("Create Stagefrightplayer");            p = new Stagefrightplayer;        Break            Case NU_PLAYER:ALOGV ("Create Nuplayer");            p = new Nuplayerdriver;        Break            Case TEST_PLAYER:ALOGV ("Create TEST PLAYER stub");            p = new Testplayerstub ();       Break            Case AAH_RX_PLAYER:ALOGV ("Create [email protected] RX PLAYER");            p = Createaah_rxplayer ();        Break            Case AAH_TX_PLAYER:ALOGV ("Create [email protected] TX PLAYER");            p = Createaah_txplayer ();            Break, #ifdef Build_with_mst case MST_PLAYER:ALOGV ("Create Mstplayer");            p = new Mstplayer; break; #endif default:aLOGE ("Unknown Player Type:%d", playertype);    return NULL; }

The above code may need to be constantly modified with the addition of the media type supported by the playback, so in order to meet the "open and close Design principle" (for the modification closed, the extension opens), it is necessary to implement the media Player object creation function in different mode.

An easy way to do this is to put the above code in a function that creates the player, which is also the pattern used in the previous version of ANDROID4.2 , also known as the static Factory mode of the simple factory. As shown in the following:

Static sp<mediaplayerbase> Createplayer (Player_type playertype, void* cookie, Notify_callback_f notifyFunc) {    Sp<mediaplayerbase> p;            Switch (playertype) {case SONIVOX_PLAYER:ALOGV ("Create MidiFile");            p = new MidiFile ();        Break            Case STAGEFRIGHT_PLAYER:ALOGV ("Create Stagefrightplayer");            p = new Stagefrightplayer;        Break            Case NU_PLAYER:ALOGV ("Create Nuplayer");            p = new Nuplayerdriver;        Break            Case TEST_PLAYER:ALOGV ("Create TEST PLAYER stub");            p = new Testplayerstub ();       Break            Case AAH_RX_PLAYER:ALOGV ("Create [email protected] RX PLAYER");            p = Createaah_rxplayer ();        Break            Case AAH_TX_PLAYER:ALOGV ("Create [email protected] TX PLAYER");            p = Createaah_txplayer (); Break, #ifdef Build_with_mst case Mst_player:            ALOGV ("Create Mstplayer");            p = new Mstplayer;            break; #endif Default:aloge ("Unknown Player Type:%d", playertype);    return NULL;    } sp<mediaplayerbase> p;            Switch (playertype) {case SONIVOX_PLAYER:ALOGV ("Create MidiFile");            p = new MidiFile ();        Break            Case STAGEFRIGHT_PLAYER:ALOGV ("Create Stagefrightplayer");            p = new Stagefrightplayer;        Break            Case NU_PLAYER:ALOGV ("Create Nuplayer");            p = new Nuplayerdriver;        Break            Case TEST_PLAYER:ALOGV ("Create TEST PLAYER stub");            p = new Testplayerstub ();       Break            Case AAH_RX_PLAYER:ALOGV ("Create [email protected] RX PLAYER");            p = Createaah_rxplayer ();        Break            Case AAH_TX_PLAYER:ALOGV ("Create [email protected] TX PLAYER"); p = Createaah_Txplayer ();            Break, #ifdef Build_with_mst case MST_PLAYER:ALOGV ("Create Mstplayer");            p = new Mstplayer;            break; #endif Default:aloge ("Unknown Player Type:%d", playertype);    return NULL; }

of course, you can also put the code above to create the player object into a factory class.

The phonefactory class in the ANDROID system is a simple factory class that provides Makedefaultphones,getgsmphone, getcdmaphone,getdefaultphone,makesipphone and other factory functions to create and obtain different types of Phone objects.

Although the above simple factory model can be modified in one place, but still do not meet the "open and close design principle", also does not meet the design principles for interface programming, so in the extension of the function or need to modify the relevant code.

The phonefactory factory class also has a problem: in order to create different types of phone objects you need to call different factory functions of the Phonefactory factory class, although they create the phone objects are subclasses of the Phone .

In order to solve the problem of the simple factory pattern above, we need to adopt another two Factory mode: Factory method and Abstract factory , One adopt the way of class inheritance , one adopts the method of object combination.

2 Factory method of Plant mode

The factory method pattern defines a common abstract interface in the common parent class where the object is to be created to return the object created by the concrete class, the concrete object returned by the interface is actually created in the creation function of the implementation public abstract interface of the concrete class.

Intent: Define an interface for creating objects in an abstract class, allowing concrete classes to create concrete objects.

The UML structure class diagram for the factory method is:


The Mediarouteprovider class in the media routing framework of the ANDROID system is the adoption of the factory method pattern.


Abstract classMediarouteproviderProvides a CreateRoutecontrollerPublic interface of the objectOncreateroutecontroller, used to return aMediarouteprovider.routecontrollerObjectMediarouteprovider.routecontrollerThe specific object is actually determined by theMediarouteproviderThe specific derived class in which theOncreateroutecontrollerThe function is responsible for creating, asMediarouteproviderThe derived classRegisteredmediarouteproviderIn itsOncreateroutecontrollerThe function creates a concrete type ofRegisteredmediarouteprovider.controllerOfMediarouteprovider.routecontrollerObjectMediarouteproviderThe indirect derived classSystemmediarouteprovider.legacyimplAndSystemmediarouteprovider.jellybeanimplIn the respectiveOncreateroutecontrollerfunction to create a separateMediarouteprovider.routecontrollerThe two specific objects:Systemmediarouteprovider.defaultroutecontrollerAndSystemmediarouteprovider.systemroutecontroller。


3 Factory Model Abstract Factory

The abstract factory model is responsible for creating a specific product or product family by implementing a specific factory that derives from the abstract factory. The abstract factory model can be used to create different products or series by implementing different specific factories, or to create different products through different methods of specific factories. And users only deal with the abstract factory, and do not care which factory created the specific product.

The intent of the abstract factory pattern is to provide an interface for creating a series of related or dependent objects, through which the user can create a series of related objects.



In the latest version of the ANDROID system in the media frame above the creation of the media player has adopted the abstract Factory mode. The class diagram is as follows:


whichmediaplayerfactoryFormediaplayerfactory:ifactoryof customers,mediaplayerfactoryThrough the abstract factory that it containsmediaplayerfactory:ifactoryThe abstract interfaceCreateplayerTo create different players, each specific player is created by each specific factory, such asStagefrightplayerPlayer bystagefrightplayerfactoryFactory created,nuplayerfactoryFactory creationNuplayerdriverPlayer,sonivoxplayerfactoryFactory creationMidiFilePlayer,testplayerfactoryFactory creates a player for testingtestplayerstub。 InmediaplayerfactoryEach specific player factory in the class needs to use themediaplayerfactoryOfregisterfactory_lOrregisterfactoryfunction is registered tomediaplayerfactoryclass, in order tomediaplayerfactoryClass to create a specific type of player in its factory method, depending on the playback type, to obtain a specific playback factory.

The key difference between an abstract factory and a factory method pattern is that abstract factories need to create specific factories that derive from the abstract factory, create specific products through instance methods of specific factory objects, and factory method pattern products are created by a class method in the concrete class of the product to be created.

4 Generator

Sometimes the creation of objects needs to be done in steps, then the generator pattern can be used, theUML class diagram is as follows:

There are also a number of use of generator patterns in ANDROID systems. such as Alertdialog,Uri,Notification , and other objects are created. The following is an example of creating an Alertdialog object.

  Alertdialog dialog = new Alertdialog.builder (mcontext). Settitle (r.getstring (r.string.wifi_p2p_invitation_sent            _title)            . Setview (Textentryview).            Setpositivebutton (r.getstring (R.string.ok), null)            . Create ();

5. Prototype

If you need to clone an existing object to create a new object, you should use the prototype pattern. UML The class diagram is as follows:



All classes that implement the cloneable interface in an Android system support the creation of their objects in prototype mode, such as Intent,Animation,Bundle ,componentname,Event , and other objects.

The following example creates a code snippet for a intent object that uses the prototype pattern to create its object:


/**     * Copy constructor.     *    /Public Intent (Intent o) {        this.maction = o.maction;        This.mdata = O.mdata;        This.mtype = O.mtype;        This.mpackage = O.mpackage;        This.mcomponent = o.mcomponent;        This.mflags = o.mflags;        if (o.mcategories! = null) {            this.mcategories = new arrayset<string> (o.mcategories);        }        if (O.mextras! = null) {            This.mextras = new Bundle (O.mextras);        }        if (o.msourcebounds! = null) {            this.msourcebounds = new Rect (o.msourcebounds);        }        if (o.mselector! = null) {            this.mselector = new Intent (o.mselector);        }        if (o.mclipdata! = null) {            this.mclipdata = new Clipdata (o.mclipdata);}    }    @Override Public    Object Clone () {        return new Intent (this);    }

5 single-piece mode

If a class only needs to create one instance in a process, a single-piece mode is required, and the class diagram is as follows:

In an Android system, a single-piece mode is also commonly used to maintain a unique instance of a class within a process.

such as many hardware-related system service management classes and services:ServiceManager,sensormanager,windowmanagerglobal, Wallpapermanager,accessibilitymanager,usermanagerservice,downloadmanager, Batteryservice,Connectivitymanager and so on.

The following code uses a single-piece mode to obtain a single instance of the ServiceManager class.

private static Iservicemanager sservicemanager;private static Iservicemanager Getiservicemanager () {        if ( Sservicemanager! = null) {            return sservicemanager;        }        Find the service Manager        Sservicemanager = Servicemanagernative.asinterface (Binderinternal.getcontextobject () );        return sservicemanager;    }


All rights reserved, please reprint when respect copyright clearly indicate source and link, thank you!




Adoption of design patterns in ANDROID--Create-mode

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.