Learning notes of design mode: (11) sharing mode

This note is excerpted from: https://www.cnblogs.com/PatrickLiu/p/7792973.html Record the learning process for future reference.

I. Introduction

Today, we are going to talk about the sixth pattern of structural design pattern - the sharing element pattern. First, from the name, the sharing element can be understood in this way - sharing "unit". What is the unit? Example: for graphics

For English, it is only 26 English letters; for Chinese, it is every Chinese character. We can also understand the "element" - the smallest unit of things. If these units are large and repeated, we can

In order to save memory, we cache the repeated units. In other words, the purpose of sharing yuan is to save space. For a computer, it is to save memory.

Object oriented technology solves the problem of system abstraction (system abstraction refers to writing things in the system into classes, classes can be instantiated into objects, and the system can be designed with the relationship between objects)

In most cases, this will not damage the performance of the system. However, in some special applications, because the number of objects is too large, and many of these large objects are repeated, if each pair

Creating images separately (the syntax of C ා is new) will bring the system an unbearable memory overhead, such as graphics application elements and other objects, word processing application character objects and so on.

II. Introduction to the sharing mode

Sharing mode: English name -- Flyweight Pattern; classification -- structural type.

2.1. Motivation

In software system, the problem of adopting pure object scheme is that a large number of fine-grained objects will soon fill the system, which will bring a high price of running time -- mainly referring to the cost of memory demand. How to avoid

Free from a lot of fine-grained object problems, let external clients still operate transparently in an object-oriented way?

2.2 intention

Using sharing technology to effectively support a large number of fine-grained objects. ——Design mode GoF

2.3 Structure

2.4 composition of mode

1) Abstract membership role (Flyweight): this role is the base class of all concrete membership classes, which specifies the public interface to be implemented. Operations that require an external state can be done by calling methods

Passed in as a parameter.

2) concrete flyweight: implements the interface specified by the abstract sharerole. If there is an internal state, it can be defined inside the class.

3) FlyweightFactory: this role is responsible for creating and managing the role. This role must ensure that the sharing object can be shared properly by the system. When a client object calls a

When sharing yuan objects, the role of sharing yuan factory checks whether there is a qualified sharing yuan object in the system. If it already exists, the sharing factory role provides the existing sharing objects. If it does not exist in the system

If a matching sharing object, the sharing factory role should create an appropriate sharing object.

4) Client role: this role needs to store the external status of all sharing objects.

2.5. Specific code implementation of sharing element mode

When it comes to "sharing element mode", I have a good scenario to explain. We know that there will be many fighters in the game scene of fighting. Basically, the fighters are almost the same. The biggest difference is to take them

Weapons are different. In large-scale war games, there will be a large number of soldiers coming out to fight. When we write programs, we can use "enjoy yuan" to solve the situation of a large number of soldiers.

    class Program
    {
        /// <summary>
        /// These are auxiliary types
        /// </summary>
        public enum SoldierType
        {
            Normal,
            Water
        }

        /// <summary>
        /// This type is the abstract warrior Soldier--This type is equivalent to the abstract sharing role
        /// </summary>
        public abstract class Soldier
        {
            //Initialize the soldier's name through the constructor
            protected Soldier(string name)
            {
                Name = name;
            }

            //Soldier's name
            public string Name { get; private set; }

            //Different weapons bring different vitality--This method is equivalent to abstraction Flyweight Of Operation Method
            public abstract void Fight();

            public Weapen WeapenInstance { get; set; }
        }

        /// <summary>
        /// A general type of warrior. The weapon is a rifle--Equivalent to concrete Flyweight role
        /// </summary>
        public sealed class NormalSoldier : Soldier
        {
            //Initialize the soldier's name through the constructor
            public NormalSoldier(string name) : base(name) { }

            //How to perform sharing--Namely Flyweight Type Operation Method
            public override void Fight()
            {
                WeapenInstance.Fire("Rank-and-file soldiers:" + Name + "Kill on land.");
            }
        }

        /// <summary>
        /// This is a marine with excellent weapons--Equivalent to concrete Flyweight role
        /// </summary>
        public sealed class WaterSoldier : Soldier
        {
            //Initialize the soldier's name through the constructor
            public WaterSoldier(string name) : base(name) { }

            //How to perform sharing--Namely Flyweight Type Operation Method
            public override void Fight()
            {
                WeapenInstance.Fire("Rank-and-file soldiers:" + Name + "Kill in the sea.");
            }
        }

        /// <summary>
        /// This type has nothing to do with sharing element. It can be regarded as the state of sharing element object. It needs to be defined externally.
        /// </summary>
        public abstract class Weapen
        {
            public abstract void Fire(string jobName);
        }

        /// <summary>
        /// This type has nothing to do with sharing element. It can be regarded as the state of sharing element object. It needs to be defined externally.
        /// </summary>
        public sealed class AK47 : Weapen
        {
            public override void Fire(string jobName)
            {
                Console.WriteLine(jobName);
            }
        }

        /// <summary>
        /// This type of factory is worth RMB--Amount to FlyweightFactory type
        /// </summary>
        public sealed class SoldierFactory
        {
            private static IList<Soldier> soldiers;

            static SoldierFactory()
            {
                soldiers = new List<Soldier>();
            }

            Soldier mySoldier = null;
            //Because I have two kinds of soldiers here, I can add another parameter here--Soldier type, not in the original mode.
            public Soldier GetSoldier(string name, Weapen weapen, SoldierType soldierType)
            {
                foreach (Soldier soldier in soldiers)
                {
                    if (string.Compare(soldier.Name, name, true) == 0)
                    {
                        mySoldier = soldier;
                        return mySoldier;
                    }
                }
                //We have a unique mission name here
                if (soldierType == SoldierType.Normal)
                {
                    mySoldier = new NormalSoldier(name);
                }
                else
                {
                    mySoldier = new WaterSoldier(name);
                }
                mySoldier.WeapenInstance = weapen;

                soldiers.Add(mySoldier);
                return mySoldier;
            }
        }

        static void Main(string[] args)
        {
            #region Enjoy yuan mode
            //For example, we need 100 ordinary soldiers now.
            SoldierFactory factory = new SoldierFactory();
            AK47 ak47 = new AK47();
            for (int i = 0; i < 100; i++)
            {
                Soldier soldier = null;
                if (i <= 20)
                {
                    soldier = factory.GetSoldier("Rank-and-file soldiers" + (i + 1), ak47, SoldierType.Normal);
                }
                else
                {
                    soldier = factory.GetSoldier("Rank-and-file soldiers" + (i + 1), ak47, SoldierType.Water);
                }
                soldier.Fight();
            }
            //We have so many soldiers, but we don't use a lot of memory because we cache it.
            Console.Read();
            #endregion
        }
    }

The operation results are as follows:

This model is very simple, so I won't talk much.

III. key points for the realization of the sharing mode

Object oriented solves the problem of abstraction well, but as a program entity running in the machine, we need to consider the cost of the object. Flyweight design pattern mainly solves the problem of object-oriented generation

Price problem generally does not touch the abstract problem of object-oriented.

Flyweight uses the method of object sharing to reduce the number of objects in the system, so as to reduce the memory pressure brought by fine-grained objects to the system. In the aspect of concrete implementation, we should pay attention to the processing of object state. Object

Too much of it leads to an increase in object memory overhead -- what kind of amount is large? This requires us to carefully evaluate according to the specific application, rather than conjecture.

3.1 advantages of the sharing mode

1) the advantage of sharing mode is that it can greatly reduce the number of objects in the system.

2) as the external state is used in the sharing mode, and the external state is relatively independent, it will not affect the internal state, so the sharing mode enables the sharing objects to be shared in different environments.

3.2 disadvantages of sharing mode

1) due to the need to distinguish the external state from the internal state, the application is more complicated to some extent.

2) in order to share objects, the sharing mode needs to externalize the state of sharing objects, while reading the external state makes the running time longer.

3.3. When all the following conditions are met, you can consider using the sharing mode:

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 externalized.

4) these objects can be divided into many groups according to the internal state. When the external objects are removed from the objects, each group can use only one object instead of the identity of the software system.

The system that meets the above conditions can use the sharing element mode, but using the sharing element mode requires maintaining an additional table that records all the existing sharing elements of the subsystem, which also needs to consume resources. Therefore, it is necessary to

It is worth using the sharing mode when enough sharing instances can be shared.

IV. implementation of sharing element mode in. NET

. NET has a Code Behind mechanism in C ා. It has an aspx file on the surface and a cs file on the back. Its compilation process will actually parse the aspx file into a C ා, and then compile it into a dll,

In this process, any html code we write in aspx will be converted into literal control, which is a general text control, which represents html tags. When the marks are the same,

Flyweight mode is used when building the control tree. Its application is not so frequent, we only use it when the efficiency space is really not high.

V. summary

When I first came into contact with this pattern, I felt that this pattern was not particularly difficult. It was also involved in the process of coding, but I also took many detours in the process of learning. Any design pattern has its own characteristics

Use the scene carefully. This mode is relatively used less in business systems, and more in systems such as game scenarios and character processing. As the old saying goes, use patterns iteratively. Don't

Mode for mode.

Keywords: C# less

Added by beckjo1 on Wed, 19 Feb 2020 06:44:15 +0200