Several design patterns in the work

Source: Internet
Author: User

1. Single-case mode
synchronized public static ImCache getInstance   (Context context) {      if (sInstance == null) {          sInstance = new ImCache(context);      }      return sInstance;  }  
Advantages
    • Because Singleton mode has only one instance in memory and reduces memory overhead, especially when an object needs to be created, destroyed frequently, and performance is not optimized when it is created or destroyed, the advantages of the singleton pattern are obvious.
    • Because the singleton pattern generates only one instance, it reduces the performance cost of the system, and when an object is produced that requires more resources, such as reading the configuration and generating other dependent objects, it can be solved by directly producing a singleton object when the application starts, and then using the permanent memory-resident method;
    • Singleton mode avoids multiple uses of resources, such as a write file action, because only one instance exists in memory and avoids simultaneous write operations on the same resource file.
    • Singleton mode can be used to set global access points, optimize and share resource access, for example, you can design a singleton class, responsible for all data table mapping processing.
Disadvantages
    • The singleton mode generally has no interface, the extension is very difficult, to expand, in addition to modify the code basically there is no second way can be achieved.
2.builder mode
    Imsession session = Sb.looper (Mimmodule.getlooper ()). Listener (mimmodule). config (Mimmodule.geti            Mconfig ()). Imsservice ((iimserviceinterface) Handlerfactory.getstackadaptor (Iimserviceinterface.class)) . Slmservice ((islmserviceinterface) Handlerfactory.getstackadaptor (Islmserviceinterface.class)). UriGenerator ( Mimmodule.geturigenerator ()). Mnostrategy (Mimmodule.getmnospecificstrategy ()). Chatid (Stringidgenera Tor.generatechatid (participants, Participants.size () > 1)). Participantsuri (participants). Ownpho Nenum (Mimmodule.getownphonenum ()). Subject (Event.mwelcomenote). Contributionid (Event.mcontributionid ). Conversationid (Event.mconversationid). Sdpcontenttype (Event.msdpcontenttype). Directio N (imdirection.incoming). Rawhandle (event.misdeferred null:event.mRawHandle). Capability (Mimmodul E.getchatsessioncapabiliTy ()). Sessiontype (Event.msessiontype). build (); 
    • Good encapsulation, using builder mode allows the client not to know the details of the internal composition of the product;
    • Builders are independent and easy to expand;
    • Some other objects in the system are used during object creation, which are not readily available during the creation of the Product object.
3.adapter mode
Public interface IDataAdapter {/** * This method would adapt the XML element to ProfileData * * @param element The input XM L element * @return The output profiledata */public profiledata buildprofiledata (element Element);/** * This method would a  Dapt the ProfileData to XML element * * @param profiledata the input profiledata * @param document the input w3g document, Which'll used to make element * @return the output XML element */public element Buildxmlelement (ProfileData ProfileData , document document);/** * Compare the contentvalues and return the compare result * <p> * This method is used T o Compare-profileInfo, * * @param valuesa the input contentvalues to be compared * @param valuesb the input contentval UEs to be compared * @return The Compare result: {@link compareresult} */public int compare (Contentvalues Valuesa, Content Values valuesb);p ublic string GetMimeType ();p ublic string gettagname ();p ublic string GetElementType ();p Ublic interface Compareresult {public Final static int same = 0;    Public final static int should_upadate = 1; Public final static int not_related =-1;}}
Advantages
    • Better reusability
      The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system. The adapter mode allows for better reuse of these features.

    • Better extensibility
      When implementing the adapter functionality, you can invoke the features you have developed to naturally extend the functionality of the system.

Disadvantages
    • Excessive use of the adapter, will make the system very messy, not easy to grasp the overall. For example, clearly see the call is a interface, in fact, the interior is adapted to the implementation of the B interface, a system if too many occurrences of this situation, is tantamount to a disaster. So if it's not necessary, you can refactor the system without using the adapter.
4. Observer mode
    mPersister = new ImPersister(mContext, mImModule);    addObserver(mPersister);    chatData.triggerObservers(ImCacheAction.INSERTED);    public void update(Observable observable, Object data) {        ChatData chatData = (ChatData) observable;        ImCacheAction action = (ImCacheAction) data;        if (action == ImCacheAction.INSERTED) {            insertSession(chatData);        } else if (action == ImCacheAction.UPDATED) {            onSessionUpdated(chatData);        } else if (action == ImCacheAction.DELETED) {            deleteSession(chatData);        }    }
Advantages

An abstract coupling between the observer and the observed person

5. Policy mode
private static IMnoStrategy createMnoStrategy(Context ctx) {        String mcc = getMccFromConfiguration();        String mnc = getMncFromConfigurtion();        Mno mno = new Mno(Mcc.parseMcc(mcc), Mnc.parseMnc(mnc));        Log.d(LOG_TAG, "createMnoStrategy " + mno);        if (sMnoSpecificStrategyGenerator.containsKey(mno)) {            Class<?> cls = sMnoSpecificStrategyGenerator.get(mno);            return (IMnoStrategy) cls.getConstructor(Context.class).newInstance(ctx);        }

The strategy mode is mainly used to separate the algorithm, according to the same behavior abstraction to do different specific policy implementation.
The advantages and disadvantages of the strategy model can be seen through the above:

Advantages:
    • The coupling degree is relatively low and the expansion is convenient.
    • The operation package is also more thorough and the data is more secure.
Disadvantages:
    • As the strategy increases, the subclasses become more numerous.
6.proxy mode
 ICapabilityServiceEventListener.Stub mEventProxy = new             ICapabilityServiceEventListener.Stub() {       @Override       public void onOwnCapabilitiesChanged() throws RemoteException   {          if (mRelay == null) {              Log.d(LOG_TAG, "no listener for ICapabilityServiceEventListener");              throw new RemoteException();          } else {              mRelay.onOwnCapabilitiesChanged();          }      }  

Increased localization extensibility for objects, increased access control

7. Combination Mode

ServiceModuleManagerOverall management of each module

Advantages
    • Without destroying the package, the whole class is loosely coupled to the local class and is relatively independent of each other.
    • Has a good scalability.
    • Supports dynamic composition. At run time, the whole object can select different types of local objects.
      The whole class can wrap the local class, encapsulate the interface of the local class, and provide a new interface.
Disadvantages
    • The whole class cannot automatically get the same interface as the local class.
    • When you create an object of a whole class, you need to create an object of all local classes.
8. Decoration mode
output = new BufferedOutputStream(new FileOutputStream (mRequest.mFilePath, mTransferred > 0), bufferSize);
Advantages
    1. You can extend the functionality of an object in a dynamic way by selecting different adorners at run time to achieve different behaviors.
    2. By using different decorative classes and arranging combinations of these decorations, you can create a combination of many different behaviors. You can decorate the same object with more specific decorative classes to get more powerful objects.
    3. The concrete component class and the concrete adornment class can change independently, the user may add the new concrete component class and the concrete adornment class according to the need, in the use and then the combination, the original code does not need to change, conforms to "the opening and closing principle".
9. State mode
EVENT_SEND_MESSAGE   -->InitialState          MessageBase imMsg = (MessageBase) msg.obj;          onStartSession(imMsg, mIsRejoinable);   -->EstablishedState          onSendImMessage((MessageBase) msg.obj);   -->ClosingState          ....

It will localize the behavior associated with a particular state and separate the behavior of different states

Several design patterns in the work

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.