. NET design Pattern Example Singleton pattern (Singleton pattern)

Source: Internet
Author: User

Introduction of the Singleton mode (Brief Introduction)

Singleton mode (Singleton pattern), which guarantees that a class has only one instance, and provides a global access point to access it. Singleton mode because Singleton encapsulates its only instance, it can strictly control how a customer accesses it and when to access it.

Ii. Problem Solving (what to Solve)

Consider using singleton mode when a class allows only one instance to be created.

Three, single case pattern Analysis 1, single-case pattern structure

Singleton class, which defines a private variable instance; Private constructor Method Singleton () and Method getinstance ();

Private variable instance:

private static Singleton instance;

Private constructor Method Singleton (), you cannot use the New keyword to create an instance of this class.

private Singleton()
{
}

Method getinstance (), which is the only global access point for an instance of this class.

public static Singleton GetInstance()
{
    //如实例不存在,则New一个新实例,否则返回已有实例
    if (instance == null)
    {
        instance = new Singleton();
    }
    return instance;
}

2. Code

1, single case mode class singleton

public class Singleton
{
private static Singleton instance;
 
<summary>
Create a static read-only process helper when the program is running
</summary>
private static readonly Object _object = new Object ();
 
<summary>
The constructor method is private, and the foreign key cannot instantiate this class through the new class
</summary>
Private Singleton ()
{
}
<summary>
This method is the only global access point for this class of instances
(Double plus lock double-check Locking)
</summary>
<returns></returns>
public static Singleton getinstance ()
{
First determine if the instance exists, there is no additional lock processing
if (instance = = null)
{
The part of the program with the lock at the same time has only one thread to enter,
Lock (_object)
{
If the instance does not exist, then new instance is returned, otherwise an existing instance
if (instance = = null)
{
Instance = new Singleton ();
}
}
}
return instance;
}
}

 2、客户端代码

static void Main(string[] args)
{
    Singleton singleton1 = Singleton.GetInstance();
    Singleton singleton2 = Singleton.GetInstance();
    if (singleton1 ==singleton2)
    {
        Console.WriteLine("实例singleton1与实例singleton2相同!");
    }
    Console.ReadKey();
}

3. Example running result

Four Example Analysis (Example) 1, scene

In the mail sending mechanism, you need to log the messages that have been sent. Only one process is allowed to operate on the TXT document at the same time, and a singleton mode is more appropriate. Structure as shown

Writemaillog (String message) method: Record mail to send log to file.

_helper, _filelock: Create 2 static read-only process helpers when the program runs

2. Code

1, Class Maillog

public class Emaillog
{
private static Object _helper = new Object ();
private static Emaillog _instance;
private static Object _filelock = new Object ();
 
Private Emaillog ()
{}
 
public static Emaillog getinstance ()
{
Lock (_helper)
{
if (_instance = = null)
{
_instance = new Emaillog ();
}
}
return _instance;
}
 
<summary>
Send mail Log
</summary>
<param name= "message" > Information </param>
public void Writeemaillog (String message)
{
String FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "Mail.txt";
StreamWriter SW = null;
FileStream fs = null;
Lock (_filelock)
{
if (! File.exists (FilePath))
{
FS = System.IO.File.Create (FilePath);
SW = new StreamWriter (FS, Encoding.UTF8);
Sw. WriteLine ("--------------------------------------------------------------------------");
Sw. WriteLine (message);
Sw. Flush ();
Sw. Close ();
}
Else
{
FS = new FileStream (FilePath, filemode.append);
SW = new StreamWriter (FS, Encoding.UTF8);
Sw. WriteLine ("--------------------------------------------------------------------------");
Sw. WriteLine (message);
Sw. Flush ();
Sw. Close ();
}
}
}
}

2. Client code

static void Main(string[] args)
{
    EmailLog w1 = EmailLog.GetInstance();
    w1.WriteEmailLog("发送Mail给灵动生活...");
    EmailLog w2 = EmailLog.GetInstance();
    w2.WriteEmailLog("发送Mail给James Hao...");
}

3. Example running result

V. Summary (Summary)

In this paper, the concept of the Singleton pattern (Singleton pattern) and its design structure diagram are simply described, as well as a log instance of the mail mechanism. Singleton mode is more commonly used. Relatively simple design pattern

. NET design Pattern Example Singleton pattern (Singleton pattern)

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.