C # Design Pattern System class: Hengyuan mode

Source: Internet
Author: User

First, Introduction

In the process of software development, if we need to reuse an object, if we repeatedly use new to create this object, so that we need to apply memory space more than once in memory, which may occur in memory usage more and more cases, the problem is very serious, However, Hengyuan mode can solve this problem, let's look at how the Heng Yuan model solves this problem.

Second, enjoy the meta-model of the detailed introduction

Now that the Hengyuan pattern solves the problem of reusing new object creation, let's analyze how to solve the problem above, since all are the same object, can you just create an object, and then the next time you need to create this object, let it directly use the object that has already been created? This means that an object is shared. This is also the essence of the implementation of Hengyuan mode.

2.1 Definitions

After introducing the essence of the enjoy meta model, let's take a look at the formal definition of the meta-mode:

Hengyuan mode-The use of shared technology to effectively support a large number of fine-grained class instances to represent data, Hengyuan mode can avoid a large number of acquaintance class overhead, in the software development process if a large number of fine-grained class instances to represent the data, and these instances in addition to a few parameters are basically the same, At this point, you can use the Hengyuan mode to drastically reduce the number of instances that require classes. If you can move these parameters (referring to the different parameters of these class instances) to the outside of the class instance, they are passed in as much as possible in the method invocation, so that the number of individual instances can be greatly reduced by sharing, however we call the parameters outside the class instance the external state of the Hengyuan object, and the Hengyuan object internal parameters are called internal states

    • Internal state: The shared part that is inside the Hengyuan object and does not change as the environment changes
    • External objects: Parts that can be shared as the environment changes.

2.2 Heng Yuan Model structure diagram

2.3 The composition of the Heng Yuan model

    • Abstract Hengyuan Role (Flyweight): This role is the base class for all concrete Hengyuan classes, specifying the public interfaces that need to be implemented for these classes, and those that require an external state can be passed by invoking a method parameter.
    • Specific Hengyuan role (Concreteflyweight): Implements the interface specified by the abstract Hengyuan role, and if it is internal, it can be defined inside the class.
    • Hengyuan Factory Role (Flyweightfactory): This role is responsible for creating and managing the Heng Meta role, this role guarantees that Hengyuan objects can be shared, when a client invokes a Heinz object, the Hengyuan factory role checks whether the system already has a compliant Hengyuan object, if it already exists, Returns a Hengyuan object and re-creates a Heinz object if it does not exist
    • Client role: This role needs to store the external state of the Hengyuan object

2.4 Heng Yuan Pattern Code implementation

The flyweight class, which is a superclass or interface of all specific Hengyuan classes, through which flyweight can accept and act on an external state

 Public Abstract class Flywieght    {public        abstractvoid operation (int extrinsicstate);    }
View Code

Concreteflyweight is to inherit the flyweight superclass or implement the flyweight interface and increase the storage space for the internal state.

    Public class Concreteflyweight:flywieght    {public        overridevoid operation (int Extrinsicstate)        {            Console.WriteLine (" specific " +extrinsicstate);}    }
View Code

Unsharedconcreteflyweight refers to flyweight subclasses that do not need to be shared, because the flyweight interface makes sharing possible, but it does not force sharing

     Public class Unsharedconcreteflyweight:flywieght    {public        overridevoid operation (int extrinsicstate)        {            Console.WriteLine (" non-shared specific flywieght" +extrinsicstate);        }    }
View CodeFlyweightfactory, a Heng Yuan factory, is used to create and manage flyweight objects, which are primarily used to ensure reasonable sharing of flyweight, when a user requests a flyweight, The Flyweightfactory object provides a created instance or creates one (if it does not exist)
    Public  classflyweightfactory {PrivateHashtable flyweights =NewHashtable (); PublicFlyweightfactory () {flyweights. ADD ("X",NewConcreteflyweight ()); Flyweights. ADD ("Y",NewConcreteflyweight ()); Flyweights. ADD ("Z",NewConcreteflyweight ()); } PublicFlywieght Getflyweight (stringKey) {return((Flywieght) flyweights[key]); }    }
View Code

Client code

    classprogram {Static voidMain (string[] args) {intExtrinsincstate = 10; Flyweightfactory f =NewFlyweightfactory (); Flywieght FX = F.getflyweight ("X"); Fx.            Operation (--extrinsincstate); Flywieght fy = f.getflyweight ("Y"); Fy.            Operation (--extrinsincstate); Flywieght FZ = F.getflyweight ("Z"); Fz.            Operation (--extrinsincstate); Unsharedconcreteflyweight uf =NewUnsharedconcreteflyweight (); uf.            Operation (--extrinsincstate);        Console.read (); }    }
View Code

Results indicate

Specific 9 specific 8 specific 7 non-shared specific Flywieght6
View Code third, the realization of the mode of enjoyment of the main points:

Object-oriented is a good solution to the problem of abstraction, but as a program entity running in a machine, we need to consider the cost of the object. Flyweight design pattern mainly solves the object-oriented cost problem, and generally does not touch the object-oriented abstraction problem.
Flyweight uses object sharing to reduce the number of objects in the system, thereby reducing the memory pressure on the system from fine-grained objects. In the concrete implementation aspect, must pay attention to the object state processing.
The number of objects is too large to cause an increase in object memory overhead-What is the size? This requires careful assessment of the specific application, not the assumption.

    • Benefits of the Enjoy meta model
    1. The advantage of the enjoy meta-mode is that it can greatly reduce the number of objects in the system.
    2. Meta-mode because of the external state, the external state is relatively independent and does not affect the internal state, so the enjoy meta-mode enables the sharing of meta-objects can be shared in different environments.
    • Disadvantages of the enjoy meta model
    1. The Yu Yuan pattern needs to differentiate between the external state and the internal state, making the application somewhat more complex.
    2. In order for objects to be shared, the enjoy meta-mode requires the state of the enjoy meta-object to be externally, while reading the external state makes the runtime
    • Consider using the enjoy meta-mode when all of the following conditions are met:
    1. There are a large number of objects in a system;
    2. These objects consume a lot of memory;
    3. Most of the states in these objects can be externally
    4. These objects can be divided into groups according to the internal state, and when the external objects are removed from the object, each group can use only one object instead of the software system to not rely on the identity of these objects.

The system that satisfies the above conditions can use the enjoy meta mode. However, using the enjoy meta-mode requires the additional maintenance of a table of all the shares that the record subsystem already has, which also consumes resources, so it should be worthwhile to use the enjoy meta-mode when there are enough shared meta-instances to share.

Use patterns through iterations, not patterns for patterns

C # Design Pattern System class: Hengyuan mode

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.