Singleton mode in C #

Source: Internet
Author: User

Generally, Singleton is just like this.

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

But today I learned a C # unique Singleton statement:

class sealed Singleton {public static readonly Singleton  instance = new Singleton();private Singleton(){}}

This method is simple and practical, greatly reducing the amount of code.

However, the disadvantage is that it cannot be inherited and initialized at startup, and initialization cannot be delayed.

 

In this way, I wrote a simple loadbalance class.

public sealed class LoadBalancer{    public static readonly LoadBalancer balancer = new LoadBalancer();    private ArrayList servers = new ArrayList();    private Random random = new Random();    protected LoadBalancer()     {        servers.Add("SERVER I");        servers.Add("SERVER II");        servers.Add("SERVER III");        servers.Add("SERVER IV");        servers.Add("SERVER V");    }    public string Server     {        get         {            int i = random.Next(servers.Count);            return servers[i].ToString();        }    }}class Program{    static void Main(string[] args)    {        LoadBalancer b1 = LoadBalancer.balancer;        LoadBalancer b2 = LoadBalancer.balancer;        LoadBalancer b3 = LoadBalancer.balancer;        LoadBalancer b4 = LoadBalancer.balancer;        if (b1 == b2 || b2 == b3 || b3 == b4)            Console.WriteLine("Same instance");        Console.WriteLine(b1.Server);        Console.WriteLine(b2.Server);        Console.WriteLine(b3.Server);        Console.WriteLine(b4.Server);        Console.ReadLine();    }}

The call result is:

 

Same instance

Server III

Server I

Server IV

Server IV

 

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.