Detailed design pattern: singleton pattern

This article takes a look at the third most commonly used mode in the creation mode: the singleton mode. It is still to look at the two pictures first, review the mode type, and deepen the memory.

definition:

Singleton mode: Ensure that a class has only one instance , and provide a global access point to access this unique instance .

Singleton Pattern: Ensure a class has only one instance, and provide a global point of access to it.

Main points:

A class can have only one instance

You must create this instance yourself

must provide this instance to the entire system itself

The simplest practical case is the task manager in the windows operating system, and the uniqueness of load balancing.

structure:

Classification:

Hungry-style singleton class: no need to consider the problem of simultaneous access by multiple threads; call speed and response time are better than lazy-style singletons; resource utilization efficiency is not as good as lazy-style singletons; system loading time may be longer

class EagerSingleton 
{ 
    private static EagerSingleton instance = new EagerSingleton(); 
    private EagerSingleton() { } 
    public static EagerSingleton GetInstance() 
    {
        return instance; 
    }
}

Lazy-style singleton class: implements lazy loading; must deal with the problem of multiple threads accessing at the same time; needs to be controlled by mechanisms such as double-check locking, which will cause system performance to be affected to a certain extent

class Singleton 
{
    private static Singleton instance=null;  
    private Singleton()
    {	
    }
	
    public static Singleton GetInstance() 
    {
        if(instance==null)
            instance=new Singleton();	
        return instance;
    }
}

Lazy style to prevent repeated calls by different processes, you can double check the lock:


class LazySingleton 
{ 
    private static LazySingleton instance = null; 

    //程序运行时创建一个静态只读的辅助对象
    private static readonly object syncRoot = new object();

    private LazySingleton() { } 

    public static LazySingleton GetInstance() 
    { 
        //第一重判断,先判断实例是否存在,不存在再加锁处理
        if (instance == null) 
        {
            //加锁的程序在某一时刻只允许一个线程访问
            lock(syncRoot)
            {
                //第二重判断
                if(instance==null)
                {
                    instance = new LazySingleton();  //创建单例实例
                }
            }
        }
        return instance; 
    }
}

Class Diagram:

applicability:

The system only needs one instance object , or only one object is allowed to be created because of too much resource consumption
A single instance of a client calling class is only allowed to use one public access point , and the instance cannot be accessed through other means than the public access point

advantage:

Provides controlled access to unique instances
Can save system resources and improve system performance
Allow variable number of instances ( multiple instance classes )

shortcoming:

Difficult to scale (lack of abstraction layer)
Singleton class has too many responsibilities
Due to the automatic garbage collection mechanism, the state of shared singleton objects may be lost


Case 1: (.NET code)

using System;

namespace SingletonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建四个LoadBalancer对象
		    LoadBalancer balancer1,balancer2,balancer3,balancer4;
		    balancer1 = LoadBalancer.GetLoadBalancer();
		    balancer2 = LoadBalancer.GetLoadBalancer();
		    balancer3 = LoadBalancer.GetLoadBalancer();
		    balancer4 = LoadBalancer.GetLoadBalancer();
		
		    //判断服务器负载均衡器是否相同
		    if (balancer1 == balancer2 && balancer2 == balancer3 && balancer3 == balancer4) 
            {
			    Console.WriteLine("服务器负载均衡器具有唯一性!");
		    }
		
		    //增加服务器
		    balancer1.AddServer("Server 1");
		    balancer1.AddServer("Server 2");
		    balancer1.AddServer("Server 3");
		    balancer1.AddServer("Server 4");

            //模拟客户端请求的分发,如果输出结果全为同一个server,可以将i适当放大,例如改为"i < 100"
		    for (int i = 0; i < 10; i++) 
            {
                string server = balancer1.GetServer();
                Console.WriteLine("分发请求至服务器: " + server);
            }
            Console.Read();
        }
    }
}
using System;
using System.Collections;

namespace SingletonSample
{
    class LoadBalancer
    {
        //私有静态成员变量,存储唯一实例
        private static LoadBalancer instance = null;
        //服务器集合
        private ArrayList serverList = null;

        //私有构造函数
        private LoadBalancer()
        {
            serverList = new ArrayList();
        }

        //公有静态成员方法,返回唯一实例
        public static LoadBalancer GetLoadBalancer()
        {
            if (instance == null)
            {
                instance = new LoadBalancer();
            }
            return instance;
        }

        //增加服务器
        public void AddServer(string server)
        {
            serverList.Add(server);
        }

        //删除服务器
        public void RemoveServer(string server)
        {
            serverList.Remove(server);
        }

        //使用Random类随机获取服务器
        public string GetServer()
        {
            Random random = new Random();
            int i = random.Next(serverList.Count);
            return serverList[i].ToString();
        }
    }
}

Case 2: (JAVA code)

public class Singleton {
    
    private static Singleton sing;

    private Singleton() {
        
    }
    
    public static Singleton getInstance() {
        if (sing == null) {
            sing = new Singleton();
        }
        return sing;
    }
}
public class Test {
    
    public static void main(string[] args) {
        Singleton sing = Singleton.getInstance();
        Singleton sing2 = Singleton.getInstance();
        
        System.out.println(sing);
        System.out.println(sing2);
    }
}

Guess you like

Origin blog.csdn.net/daobaqin/article/details/127712899