Singleton mode in Design Mode

Source: Internet
Author: User
Purpose:

Ensure that a class has only one instance and provides a global access point to it.

Implementation Method:

1.The simplest way:

Public Class Singleton
{
Private Static Singleton _ instance;
Private Singleton ()
{
Console. writeline ( " I was instantiated. " );
}
Public Static Singleton instance
{
Get
{

Return _ instance = NULL? (New Singleton (): _ instance;

}
}
}

AboveCodeEnsure three points: first, the class cannot be instantiated (private constructor); second, the class cannot be inherited (private constructor); and third, a static attribute for global access is provided.

To ensure the above three points, we can ensure that one class can only provide one instance in a single thread, but it cannot be ensured in multiple threads. Let's take a look at the Code:

 

View code

Class Program
{
Static Void Main ( String [] ARGs)
{
Multwork multthread = New Multwork ();
Multthread. startmultthread ();
Console. Readline ();
}
}
Public Class Singleton
{
Private Static Singleton _ instance;
Private Static Readonly Object padlock = New Object ();
Private Singleton ()
{
Console. writeline ( " I was instantiated. " );
}
Public Static Singleton instance
{
Get
{
Return _ Instance = Null ? ( New Singleton (): _ instance;
}

}

}
Public Class Multwork
{
Private Static Readonly Object padlock = New Object ();
///   <Summary>
/// Thread work
///   </Summary>
Public Static Void Dosomework ()
{
/// Construct a display string
String Results = String . Empty;
/// Create a sigleton instance
Singleton mycounter = singleton. instance;
/// Loop call four times
For ( Int I = 1 ; I < 5 ; I ++)
{
Results + = " Thread " ;
Results + = thread. currentthread. Name. tostring ();
Results + = " \ N " ;
}
}
Public Void Startmultthread ()
{
Thread thred0 = thread. currentthread;
Thred0.name = " Main thread " ;
Thread thread1 = New Thread ( New Threadstart (dosomework ));
Thread1.name = " Thread1 " ;
Thread1.start ();
Thread thread2 = New Thread ( New Threadstart (dosomework ));
Thread2.name =" Thread2 " ;
Thread2.start ();
Thread thread3 = New Thread ( New Threadstart (dosomework ));
Thread3.name = " Thread3 " ;
Thread3.start ();
Dosomework ();
}

We opened three new threads (including four main threads) and found that the singleton instance was instantiated four times. That is to say, each thread instantiated Singleton independently, this violates the original intention of the singleton model.

 

2.Inert instantiation

To solve the thread security problem, we can add a lock in the singleton to ensure that only one thread can be accessed at a time. Once an instance exists, the singleton class will not be instantiated, re-design the singleton Class Code as follows:

 

View code

Public Class Singleton
{
Private Static Singleton _ instance;
Private Static Readonly Object padlock = New Object ();
Private Singleton ()
{
Console. writeline ( " I was instantiated. " );
}
Public Static Singleton instance
{
Get
{
Lock (Padlock)
If (_ Instance = Null )
_ Instance = New Singleton ();
Return _ Instance;

}

}
}

After running the code in this way, no matter how many threads are started, only one instance of the class can be guaranteed.

3.Type constructor method (or static constructor method)

The advantage of this method is that the thread security should be handed over to the CLR, which is also a singleton design method recommended in. net. The Code is as follows:

 

View code

Public Class Singleton
{
Private Static Singleton _ instance = Null ;
Static Singleton ()
{
Console. writeline ( " I was instantiated. " );
}
Private Singleton ()
{
}
Public Static Singleton instance
{
Get
{
If (_ Instance = Null )
_ Instance = New Singleton ();
Return _ Instance;

}
}
}

In short, the above is the method that I often use in projects. Of course, there are other more implementation methods. You can refer to other great examples in the garden.Article, Such as the design pattern series of terrylee: http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

 

 

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.