Design pattern in a comprehensible way------Flyweight pattern

Source: Internet
Author: User

Mode motive


Object-oriented technology solves some of the flexibility or scalability problems, but in many cases you need to increase the number of classes and objects in the system. When the number of objects is too large, it will lead to high operating costs, resulting in performance degradation and so on.
The mode of enjoyment was born to solve this kind of problem. the enjoy meta-mode enables the reuse of identical or similar objects through shared technology .

The same content that can be shared in the intrinsic mode is called the internal state , while those that require an external environment to set up that cannot be shared are called External states (extrinsic state). Because of the distinction between internal and external states, you can set different external states so that the same objects can have some different characteristics, and the same internal state can be shared.
The Factory mode is typically present in the enjoy meta-mode, and it is necessary to create a Flyweight to maintain a pool of privileges to store the shared meta objects with the same internal state.
The internal state of the object is shared in the enjoy meta-mode, and the external state needs to be set through the environment. In practice, the internal state of being able to share is limited, so the enjoyment meta-object is generally designed to be a smaller object, which contains fewer internal states, which are also known as fine-grained objects. The purpose of the enjoy meta-mode is to use shared technologies to enable the reuse of a large number of fine-grained objects .

Pattern definition
Flyweight Pattern: Use sharing technology to effectively support the reuse of a large number of fine-grained objects. The system uses only a small number of objects, and these objects are very similar, the state changes very small, you can achieve multiple reuse of objects. Because the enjoy meta mode requires that the object that can be shared must be a fine-grained object, it is also known as lightweight mode, which is an object-structured pattern.
Flyweight pattern:use sharing to support large numbers of fine-grained objects efficiently.
Frequency of Use:low
UML diagram

Pattern structure
The enjoy meta mode contains the following roles:
Flyweight: Abstract enjoy meta class
Concreteflyweight: Specific class of classes to enjoy
Unsharedconcreteflyweight: Non-shared specific class of privileges
Flyweightfactory: Enjoy the Yuan factory class

Pattern Analysis
The enjoy meta-mode is a design mode that takes system performance into account, and it can save memory space and improve the performance of the system by using the enjoy meta-mode.

The core of the enjoy meta-factory class, the benefit of the meta-factory class is to provide a pool for the enjoyment of the meta-object, the user needs the object, first obtained from the pool of enjoyment, if the pool does not exist, a new object is created to return to the user, and in the pool to save the new objects.

Enjoy meta-mode efficiently supports a large number of fine-grained objects in a shared way, and the key to sharing the meta-object is to differentiate between internal states (Internal State) and external states (External State).
(1) The internal state is a state that is stored inside the shared meta object and does not change with the environment, so the internal state can be shared.
(2) The external state is a state which changes with the environment and cannot be shared. The external state of the enjoy meta object must be saved by the client and then passed in to the inside of the object when it needs to be used after the object is created. An external state is independent from the other external state.

Pattern Instances and parsing
Site Share Code
System structure

Flyweight: Abstract enjoy meta class WebSite.cs

namespace flyweightpattern{    //  Web abstract class      WebSite    {          Public Abstract void User (user user);}    }

User.cs

 namespace   flyweightpattern{ public  class   User { private  string   name;  public  User (string   name { this . Name = name;  public  string   Name { get  {return   name; }        }    }}

Concreteflyweight: Specific class ConcreteWebSite.cs

usingSystem;namespaceflyweightpattern{classConcretewebsite:website {Private stringName ="";  PublicConcretewebsite (stringname) {             This. Name =name; }         Public Override voidUser (user user) {Console.WriteLine ("website Category:"+ name +"User:"+user.        Name); }    }}

Flyweightfactory: Enjoy the Yuan factory class WebSiteFactory.cs

usingSystem.Collections;namespaceflyweightpattern{classWebsitefactory {PrivateHashtable flyweights =NewHashtable (); //Get Site Categories         PublicWebSite Getwebsitecategory (stringkey) {            if(!flyweights. ContainsKey (key)) flyweights. ADD (Key,NewConcretewebsite (key)); return((WebSite) flyweights[key]); }        //get the total number of site classifications         Public intGetwebsitecount () {returnflyweights.        Count; }    }}

Client: Customer Class

usingSystem;namespaceflyweightpattern{classProgram {Static voidMain (string[] args) {websitefactory F=Newwebsitefactory (); WebSite FX= F.getwebsitecategory ("Product Show"); Fx. User (NewUser ("Side Dishes")); WebSite FY= F.getwebsitecategory ("Product Show"); Fy. User (NewUser ("Big Bird")); WebSite FZ= F.getwebsitecategory ("Product Show"); Fz. User (NewUser ("Jiao Jiao")); WebSite FL= F.getwebsitecategory ("Blog"); Fl. User (NewUser ("old Urchin .")); WebSite FM= F.getwebsitecategory ("Blog"); Fm. User (NewUser ("Peach Valley Six Cents")); WEBSITE fn= F.getwebsitecategory ("Blog"); Fn. User (NewUser ("make Fox")); Console.WriteLine ("the total number of site categories received is {0}", F.getwebsitecount ());        Console.read (); }    }}

Model Pros and cons
Benefits of the Enjoy meta model
The advantage of the enjoy meta-mode is that it can greatly reduce the number of objects in memory, so that the same object or similar objects are saved in memory only one copy.
The external state of the enjoy meta-mode is relatively independent, and does not affect its internal state, allowing the enjoyment meta-object to be shared in different environments.

Disadvantages of the enjoy meta model
The "Enjoy meta" mode makes the system more complex and requires the separation of internal and external states, which complicates the logic of the program.
? In order for objects to be shared, the enjoy meta-mode requires the state of the object to be externally instantiated, while the read external state makes the run time longer.

Mode applicable environment
You can use the enjoy meta mode in the following situations:
? A system with a large number of identical or similar objects, due to the large use of such objects, resulting in a large amount of memory consumption.
? Most of the state of an object can be externally passed in to an object.
? Using the enjoy meta-mode requires maintaining a pool of privileges that stores the metadata of the object, which consumes resources, so it should be worthwhile to use the enjoy meta-mode when reusing the object multiple times.

"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).

"References"
Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu
http://www.dofactory.com/Patterns/Patterns.aspx. NET Design Patterns
Http://www.cnblogs.com/zhenyulu Blog Lu Zhenyu
Http://www.cnblogs.com/terrylee Blog Li Huijun
http://www.cnblogs.com/anlyren/Blog Anlyren
Http://www.cnblogs.com/idior Blog Idior
Http://www.cnblogs.com/allenlooplee blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92
http://www.cnblogs.com/umlonline/Blog Zhang
http://www.cnblogs.com/lovecherry/Blog Lovecherry

Design pattern in a comprehensible way------Flyweight pattern

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.