Review design patterns (1) -- flyweight)

Source: Internet
Author: User
Tags reflector

1. All things in the world are objects

A software engineering major student is blocked from the university campus and asked him what is object-oriented. He will tell you that everything in the world is an object.

The world is so big that everything is more than anything else. Go to the stars of the universe, and go to the bacterial virus. All are objects.

The girl is still pale and fragrant.

The boy was so happy with his close eyes.

This is sharing!

2. Object explosion

There are countless molecules between respiration.

Each molecule is an object, and the matrix of thousands of servers is also irretrievable.

Why?

Gof: Metadata-sharing mode!

3. What is the metadata-sharing model?

Flyweight: The most lightweight Boxing Player. Minimum granularity.

Therefore, the purpose of the meta-mode is to use the sharing technology to solve the explosion of a large number of fine-grained objects.

Figure:

Iv. QQ chat of the application of the enjoy-yuan Mode

Let's assume that QQ abstracts every conversation on the server to form a class. ThereforeCodeAs follows:

ClassPeople{Private stringName;Private intAge;Public StringName {Get{ReturnName ;}}Public intAge {Get{ReturnAge ;}Set{Age =Value;}}PublicPeople (StringName,IntAge ){This. Name = Name;This. Age = age ;}}

Class  Chat { Private  People Boy; Private  People Girl; Private string Chatcontent; Public Chat ( People P1, People P2 ){ This . Boy = p1; This . Girl = P2 ;} Public String Chatcontent {Get { Return Chatcontent ;} Set {Chatcontent = Value ;}} Public  People Boy { Get { Return Boy ;}} Public  People Girl { Get { Return Girl ;}}}

If you instantiate the chat as an object every time you chat, as follows:

 
ClassProgram{Static voidMain (String[] ARGs ){PeopleBoy =NewPeople("Prettyboy", 20 );PeopleGirl =NewPeople("Beautifulgirl", 18 );ChatChat =NewChat(Boy, girl); chat. chatcontent ="I love you"; Chatserver. Send (CHAT );}}

In this case, the server needs to initialize an object each time. When the chatserver sends the chat record to the client, the object becomes a spam object. In this way, millions of chat times per hour will result in millions of object spam. The garbage collector GC will need to keep working to recycle objects.

This has a huge impact on efficiency. So we can try to solve this problem by using the metadata mode.

Their chat parties are unchanged. Therefore, we can maintain such a chat object set on the server side. If the chat object already exists, then we will reuse the chat object. This not only reduces the memory garbage, but also saves the time to create objects.

The Code is as follows:

 Class  Flyweightfactory { Private  Idictionary < String , Chat > Cache = New  Dictionary < String ,Chat > (); Private void Add ( Chat C) {cache. Add (C. Boy. Name + "_" + C. Girl. Name, c );} Public  Chat Getchat ( People Boy, People Girl ){ If (! Cache. containskey (boy. Name + "_" + Girl. Name) {cache. Add (boy. Name + "_" + Girl. Name,New  Chat (Boy, girl ));} Return Cache [Boy. Name + "_" + Girl. Name] ;}}

Therefore, access the flyweightfactory from the client.

This effectively controls the number of objects.

5. Typical. NET Framework Application in the metadata-string

(For more information, see reflector. How can I find the code of string assignment in reflector? For example, string S = "111"; the Code in this step)

Well, let's take a look at the application of the metadata model in. NET Framework.

String is a special reference object in both. NET and Java.

We can imagine the following code:

String S = "Hello world ";

String S1 = "Hello world ";

Is it necessary to apply for a memory every time and then save the string? Is it very inefficient? As we know, strings are often very short in actual use. They are usually displayed directly to the customer after being read. Then the string's life ends and becomes garbage. Is it like the QQ chat we just talked about?

Therefore, in. NET and Java, string is designed in the unchanged mode.

Let's briefly analyze the string resident mechanism: After the CLR is loaded, A hashtable will be created in the managed heap of systemdomain to maintain the string.

The simulated code is as follows: (pseudo code)

 
HashtableTable;If(! Table. Contains ("Hello World") {Table. Add ("Hello World",&(NewString("Hello World")));}Return* (Table ["Hello World"]);

The Code is a bit messy. Let me explain it.

That is to say, I am simulating a string S = "Hello World" process. The process is: first, he goes to hashtable to check whether there is a "hello World" item in the key. If no heap memory exists, allocate a heap memory, store the string, and store the address as the value in hashtable. If yes, find the address corresponding to the string and retrieve the value from the address.

Use a hashtable to control the number of string objects. Do you understand this time?

6. Extension of the shared element model-Application of the Object pool

As we have said before, whether it is a string or an object, the meta mode checks whether the object exists. As long as it exists, it will be reused.

Is there such a situation?

A large number of clients access the same server during failover. If there is only one object at this time, it will cause some concurrency problems. My language is not clear. Simply put, when an object is accessed, it must lock itself and prevent other customers from referencing it.

If only one object is maintained at this time, a large number of clients will be in the waiting queue. Therefore, we need to maintain an object pool and allow multiple objects of a class to be maintained in the object pool. To balance the server space and client wait time.

Therefore, we used to maintain a cache whose value is object in dictionary. Now, we need to maintain a cache whose value is list <Object> in dictionary. This list should be a limited number and can store arrays of the same type of objects.

The Code is as follows: (refer to the <design mode -- C #-based engineering implementation and expansion> of crayon Smith)

 Class  Objectcache { Private Static  Idictionary < Type ,Object > Cache; Static Objectcache () {cache = New  Dictionary < Type , Object > ();} Public bool Trytogetobejct <t> ( Out T item, Out bool Increasable) Where T: Class , Ipoolable , New () {Trytoaddobject <t> (); Return (Cache [ Typeof (T)] As  Sizerestrictedlist <T>). Acquire ( Out Item, Out Increasable );} Private void Trytoaddobject <t> () Where T: Class , Ipoolable , New (){ If (! Cache. containskey ( Typeof (T) {cache. Add ( Typeof (T ), New  Sizerestrictedlist <T> ());}}}
Public boolAcquire (OutT item,Out boolIncreasable) {increasable = cache. Count> = configuration. Max?False:True; Item =Null;If(Cache. Count <= 0 ){Return false;}Foreach(T cacheitemInCache ){If(Cacheitem! =Null& Cacheitem. Unoccupied) {item = cacheitem;Return true;}}Return false;}

7. from micro to macro-How small is flyweight?

As we mentioned above, flyweight is used to solve the reuse problem of fine-grained objects. So let's think about how small it is to be fine-grained?

In the previous article, we have been solving the problem of Object reuse. So let's think about it in the macro direction.

Einstein's theory of relativity: everything in the world is relative. Nothing is absolutely big, only relatively small. So let's think like this.

Can we reuse a module or a sub-system?

8. Example 1 and Example 3-from Yuan-sharing to singleton

In fact, in a certain sense, I personally think that the singleton mode is the same as the original intention of the Yuan mode. They are both a space-and performance-based model. They both need to control the number of objects, and the implementation method is essentially similar, that is, to first query whether the object exists and then return the object.

From the perspective of the metadata model, we can also use the singleton model:

1. We can control multiple instances instead of single instances. For example, it is similar to the purpose of my previous Object pool.

2. Is a singleton an object? We can also take the subsystem and module Singleton!

Let's look at their differences:

The metadata mode is an extension of the singleton mode. The metadata mode controls the singleton of multiple objects through the metadata factory. While Singleton only solves the singleton problem!

9. Do not use the mode-when to use the yuan

I have always felt that the mode should not be used in disorder, and the mode of chaos is the learning stage. However, once we use the mode at work, it may cause terrible consequences.

So when should we use the metadata-sharing model?

1. There must be a large number of objects in the system, so it is worth using the metadata mode. Otherwise, it is not worth maintaining an object table.

2. Object creation consumes a lot of time, and the object occupies a large amount of memory. If not, let the system create it.

3. in the B/S system, I personally feel that there are relatively few applications to enjoy yuan, and the Web is stateless. In addition, we perform a series of complex logic on the client, then it is transmitted to the Web server without the need to enjoy the yuan. The main application of the yuan is still in the local C/S and winformProgram.

The rest, such as the question about what kind of the exclusive and inner states should be used for yuan, cannot you use the yuan if the situation is not met. Therefore, I am not talking about the definition of the mouth.

10. Meta Summary

Flyweight: uses the sharing technology to effectively support a large number of fine-grained objects.

It's time to get up and work overtime .........

Thank you for your attention and hope you can give me more advice!

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.