22nd Chapter, the mode of enjoying the yuan
Enjoy meta-mode is one of the structural design patterns, which is an implementation of the object pool. Just like its name, share the object and avoid duplicate creation. We often String
use shared mode, so that String
objects of type cannot be changed after creation, and if two String
objects contain the same content, the JVM creates only one String
object corresponding to these two different object references.
1. Definition
Use a share to avoid the overhead of having a large number of objects with the same content. 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 state and the external state: the shared part that is inside the subject of the object and does not change with the environment can be called the internal state of the object, and the non-shared state is called the external state as the environment changes.
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
: The specific element of the object, if there is an internal state, it must be responsible for the internal state to provide storage space.
(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 all of the objects, and also need to store the corresponding external state.
4. Simple implementation
Scenario: When we buy train tickets for the new year, we need to check the situation of tickets, then if each query ticket to create a result, then will inevitably create a lot of duplicate objects, frequently to destroy them, so that the GC task heavy. Then we can use the enjoy meta-mode, cache these objects, the query when the priority to use the cache, no cache is recreated.
The first is the Ticket interface (Flyweight):
publicinterface Ticket { publicvoidshowTicketInfo(String bunk);}
Trainticket specific 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 source in the implementation of 1.Message
Because Android is event-driven, Message
a large number of objects are created through new, Message
resulting in high memory usage and frequent GC issues. Then Message
the use of the mode of enjoyment.
Message
A reference to the next is retained through the next
member variable Message
, and the last one available is Message
next
empty. This forms a list of message links . Message Pool
all idle is managed by the table header of the list, and Message
one Message
can be accessed through the method when it is used recycle()
Message Pool
, and obtain
obtained from the static method when needed Message Pool
. Assume the responsibility of the Message
3 elements of the module, that is, Flyweight
abstract and ConcreateFlyweight
role, while assuming the FlyweightFactoiy
responsibility of the pool of management objects.
So use the message recommend obtain (), do not go to new.
//1Message() //MessageMessage(); //2。使用Message.obtain() MessageMessage.obtain(); 1; //Message mess = mHandler.obtainMessage(1); 与上两行的代码一样,可以参考源码查看 mHandler.sendMessage(mess);
6. Summary 1. Advantages
(1) Greatly reduce the application-created objects, reduce the use of program memory, enhance the performance of the program.
(2) using the enjoy meta-mode, you can allow the enjoyment meta-object to be shared in different environments.
2. Disadvantages
(1) Make the system more complex. In order for objects to be shared, some States need to be externally instantiated, which complicates the logic of the program.
(2) The enjoy meta-mode will be the need, the enjoyment of the state of the meta-object, and read the external state to make the run time slightly longer.
7. Reference
1. Enjoy meta-mode
"Android source design mode analysis and actual combat" reading notes (22)