Examples of singleton patterns of C design patterns

  • 2020-11-18 06:24:22
  • OfStack

preface

Recently, I have started to put some thought into design patterns, mainly to make the code I write highly reusable and ensure the reliability of the code. A design pattern, I've come up with a definition: it's a set of code design experiences that have been used over and over again, that most people know about, that have been catalogued, and that have been cataloged. There is no doubt that design patterns are win-win-win for themselves, others and the system; Design mode makes code compilation truly engineering; Design patterns are the cornerstones of software engineering, just like the structure of a building.

Why "Design Pattern(Design patterns)"?

The root cause is code reuse and increased maintainability. So this time we'll look at design patterns, and we'll end up using the C# language as an example of how to implement these design patterns.

define

Singleton pattern is a common software design pattern. Its core structure contains only one special class, called a singleton class. The singleton pattern ensures that there is only one instance of a class in the system and the instance is easy to be accessed by the outside world, thus facilitating the control of the number of instances and saving system resources. If you want to have only one object for a class in your system, singleton mode is the best solution.

The characteristics of

1. There can only be one instance of a class
2. It must create the instance itself
3. It must provide the instance itself to the entire system.

The advantages and disadvantages

Advantages:

1. Instance control

The singleton pattern prevents other objects from instantiating copies of their own singleton, ensuring that all objects have access to only one instance.

2. The flexibility

Because classes control the instantiation process, classes have the flexibility to change the instantiation process.

Disadvantages:

1. The overhead

Although the number is small, there will still be some overhead if you check for an instance of a class every time an object requests a reference. You can solve this problem by using static initialization.

2. Possible development confusion

When working with singleton objects (especially those defined in a class library), developers must remember that they cannot instantiate objects using the new keyword. Because the library source code may not be accessible, application developers may accidentally find themselves unable to instantiate this class directly.

3. Object lifetime

The problem of deleting a single object cannot be resolved. In languages that provide memory management (such as.NET Framework based languages), only a singleton class can cause an instance to be de-allocated because it contains a private reference to the instance. In some languages (such as C++), other classes can delete object instances, but this results in dangling references in the singleton class.


/// <summary>
    /// The singleton pattern
    /// </summary>
    public class Singleton
    {
        // define 1 Static variables to hold instances of a class
        private static Singleton mySingleton;         // Define a private constructor so that an instance of the class cannot be created outside the class
        private Singleton()
        {
        }         // Define public method provision 1 Three global access points.
        public static Singleton GetInstance()
        {
            // Here, lock Well, the principle that you use can be used 1 One word encapsulates the concept of "mutual exclusion", which is also the essence of operating systems
            // In fact, when 1 When one process accesses another, the other process suspends its status first
            if (mySingleton == null)
            {
                mySingleton = new Singleton();
            }
            return mySingleton;
        }
    }

Above the implementation of the singleton pattern is problematic, when multiple users or methods to access at the same time, it will be more than one user at the same time got the results of mySingleton = = null, this is obviously not what we want, so we should be through a mutex lock this method, when many threads access at the same time, only allow one thread to enter the code that executes, and the other can only in a state of suspended.


/// <summary>
    /// The singleton pattern
    /// </summary>
    public class Singleton
    {
        // define 1 Static variables to hold instances of a class
        private static Singleton mySingleton;         // define 1 The identifiers ensure thread synchronization
        private static readonly object locker = new object();
        // Define a private constructor so that an instance of the class cannot be created outside the class
        private Singleton()
        {
        }         // Define public method provision 1 Three global access points.
        public static Singleton GetInstance()
        {
            // Here, lock Well, the principle that you use can be used 1 One word encapsulates the concept of "mutual exclusion", which is also the essence of operating systems
            // In fact, when 1 When one process accesses another, the other process suspends its status first
            if (mySingleton == null)// That's the difference
            {
                lock (locker)
                {
                    // If an instance of the class does not exist, it is created, otherwise returned directly
                    if (mySingleton == null)
                    {
                        mySingleton = new Singleton();
                    }
                }
            }
            return mySingleton;
        }
    }

In fact, in some projects, the singleton pattern has long been reflected. In the project to develop ES62en.net, this approach has been used to wrap the http context to achieve savings in computer resources.


/// <summary>
        /// Business warehouse
        /// </summary>
        public IBLL.IBLLSession BLLSession;         //--------------------- Define context properties
        #region Instance constructor Initialize the business warehouse + OperateContext()
        public OperateContext()
        {
            BLLSession = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");
        }
        #endregion         #region Http context And related properties
        /// <summary>
        /// Http context
        /// </summary>
        HttpContext ContextHttp
        {
            get
            {
                return HttpContext.Current;
            }
        }         HttpResponse Response
        {
            get
            {
                return ContextHttp.Response;
            }
        }
        HttpRequest Request
        {
            get
            {
                return ContextHttp.Request;
            }
        }
        HttpSessionState Session
        {
            get
            {
                return ContextHttp.Session;
            }
        }
        #endregion         #region Gets the current action context ( Existing in the thread, improve efficiency ) + OperateContext Current
        // <summary>
        /// Gets the current action context ( Existing in the thread, improve efficiency )
        /// </summary>
        public static OperateContext Current
        {
            get
            {
                OperateContext o = CallContext.GetData(typeof(OperateContext).Name) as OperateContext;
                if (o == null)
                {
                    o = new OperateContext();
                    CallContext.SetData(typeof(OperateContext).Name, o);
                }
                return o;
            }
        }
        #endregion

conclusion

1 at first here, and you know what on earth is the singleton pattern, actually in some projects, 1 this model has been applied, but we didn't go to found and summary, but it has been repeatedly used originally design patterns is 1 set, most people know, the classified catalog, code design experience summary. Well... This is the second time to edit. Originally, this singleton has been published for several days, but it was actually covered by my new article observer mode. I can't get the data back, so I can only finish it in a hurry.


Related articles: