"Android source code design mode analysis and actual combat" reading notes (22)

Source: Internet
Author: User

22nd Chapter, the mode of enjoying the yuan

The enjoy meta-mode is one of the structural design patterns. is an implementation of the object pool. Just like its name, share the object. Avoid creating over and over again.

We often use String shared mode. So String the type of object creation is immutable, assuming that when two String objects contain the same content, the JVM simply creates an String object corresponding to these two different object references.

1. Definition

Use a share to avoid the overhead of having the same content object in large numbers. Use the enjoy meta-mode to effectively support a large number of fine-grained objects.

2. Usage Scenarios

(1) There are a lot of similar objects in the system.

(2) Fine-grained objects have a close external state, and the internal state is not related to the environment, which means that the object has no specific identity.

(3) Scenarios where buffer pools are required.

PS: The internal and external states: shared parts that are inside the enjoyment meta-object and do not change as the environment changes. can be referred to as the internal state of the object, and vice versa as the environment changes. A non-shareable state is called an external state.

3.UML class Diagram

The enjoy meta-mode is divided into the simple-to-enjoy meta-mode and the compound-enjoy-meta model.

(1) Flyweight : An abstract base class or interface for a metadata object.

(2) ConcreateFlyweight : Detailed object of enjoyment, assuming that there is an internal state. You must be responsible for providing storage space for the internal state.

(3) UnsharadConcreateFlyweight : The object represented by the compound privilege role is not shareable and can be decomposed into a combination of multiple simple-to-enjoy meta-objects.

The simple-to-enjoy meta-mode does not have this, which is the structural difference between the two.

(4) FlyweightFactoiy : Enjoy meta-factory, which is responsible for managing the sharing of the meta-object pool and creating the privilege object.

(5) Client : Maintain a reference to the full object, and also store the corresponding external state.

4. Simple implementation

Situation: When we buy train tickets for the Spring Festival, we need to inquire about the tickets. So if you create a result every time you query your ticket, you will have to create a lot of repetitive objects. Frequently to destroy them, making the GC task heavy. Then we are able to use the enjoy meta-mode, cache these objects, the query priority to use the cache, there is no slow to create another time.

The first is the Ticket interface (Flyweight):

publicinterface Ticket {    publicvoidshowTicketInfo(String bunk);}

Trainticket detailed implementation Class (Concreateflyweight):

//Train tickets Public  class trainticket implements Ticket{     PublicString from;//Place of Origin     PublicString to;//Destination     PublicString Bunk;//Bunk     Public intPrice//Price     Public Trainticket(string from, string to) { This. from = from; This. to = to; }@Override     Public void Showticketinfo(String Bunk) {Price =NewRandom (). Nextint ( -); System.out.println ("Buy from"+ from +"to"+ to +"of"+ Bunk +"Train Ticket"+", Price:"+ price); }}

Ticketfactory Management Inquiry train Ticket (Flyweightfactoiy):

 Public classticketfactory {Staticmap<string, ticket> sticketmap =NewConcurrenthashmap<string, ticket> (); Public StaticTicketGetTicket(String from, string to) {string key = from+"-"+ to;if(Sticketmap.containskey (key)) {System. out. println ("Using Cache ==>"+ key);returnSticketmap.Get(key); }Else{System. out. println ("Create Object ==>"+ key); Ticket Ticket =NewTrainticket ( from, to); Sticketmap.put (key, ticket);returnTicket }    }}

Inquire:

final class Client {    publicstaticvoidmain(String[] args) {        Ticket ticket01 = TicketFactory.getTicket("北京""青岛");        ticket01.showTicketInfo("上铺");        Ticket ticket02 = TicketFactory.getTicket("北京""青岛");        ticket02.showTicketInfo("下铺");        Ticket ticket03 = TicketFactory.getTicket("北京""西安");        ticket03.showTicketInfo("坐票");    }}

Results

创建对象 ==> 北京-青岛购买 从 北京 到 青岛的上铺火车票, 价格:71使用缓存 ==> 北京-青岛购买 从 北京 到 青岛的下铺火车票, 价格:32创建对象 ==> 北京-西安购买 从 北京 到 西安的坐票火车票, 价格:246
5.Android implementation in source code 1.Message

Since Android is event-driven, it is assumed that Message a large number of objects are created through new Message , resulting in high memory usage, frequent GC, and so on. Then Message the use of the enjoy meta-mode.

Messagenexta reference to the next is retained through the member variable Message . The last one available is Message next empty. This forms a list of message links .

Message PoolThrough the list of the table header management of all idle Message , one Message after the use of the method can be recycle() entered Message Pool , and when required by obtain static method from the Message Pool acquisition.

MessageAssume the responsibility of the 3 elements of the module, which is Flyweight abstract. Another ConcreateFlyweight character. At the same time, it assumed the FlyweightFactoiy responsibility of the pool of management objects.

So use the message recommend obtain (), do not go to new.

//1。

Message() //MessageMessage(); //2。使用Message.obtain() MessageMessage.obtain(); 1; //Message mess = mHandler.obtainMessage(1); 与上两行的代码一样。能够參考源代码查看 mHandler.sendMessage(mess);

6. Summary 1. Strengths

(1) Greatly reduce the application-created objects, reduce the use of program memory. Enhance the performance of the program.

(2) Use the enjoy meta-mode to enable the enjoyment of Meta objects to be shared in different environments.

2. Disadvantages

(1) Make the system more complex. In order for the object to be shared, some States need to be externally instantiated. This complicates the logic of the program.

(2) The enjoy meta-mode will be the need, the enjoyment of the state of the meta-object, while reading the external state makes the execution time slightly longer.

7. References

1. Enjoy meta-mode

"Android source code design mode analysis and actual combat" reading notes (22)

Related Article

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.