Single Instance Mode

Source: Internet
Author: User
1. Introduction to singleton mode (Brief Introduction)

Singleton pattern ensures that a class has only one instance and provides a global access point to it. Singleton encapsulates its unique instance, so that it can strictly control how customers access it and when to access it.

2. What to solve)

When only one instance can be created for a class, you can consider the singleton mode.

Iii. Analysis of Singleton Mode 1. Structure of Singleton Mode

 

Singleton class, Defines a private variable instance; private constructor Singleton () and method getinstance ();

Private variable instance:

Private Static Singleton instance;

The private constructor Singleton () cannot use the new keyword to create such instances.

Private Singleton ()

{

}

Method getinstance (), which is the only global access point of the instance.

Public static Singleton getinstance ()

{

// If the instance does not exist, a new instance is created. Otherwise, an existing instance is returned.

If (instance = null)

{

Instance = new Singleton ();

}

Return instance;

}

2. Code

1. Singleton

Public class Singleton

{

Private static Singleton instance;

 

/// <Summary>

/// When the program is running, create a static read-only process Helper Object

/// </Summary>

Private static readonly object _ object = new object ();

 

/// <Summary>

/// The constructor is private. The foreign key cannot be instantiated through the New class.

/// </Summary>

Private Singleton ()

{

}

/// <Summary>

/// This method is the unique global access point of the instance.

/// (Double-Check Locking)

/// </Summary>

/// <Returns> </returns>

Public static Singleton GetInstance ()

{

// First judge whether the instance exists and no locks the instance.

If (instance = null)

{

// Only one thread is allowed to access the locked programs at the same time,

Lock (_ object)

{

// If the instance does not exist, a New instance is created. Otherwise, an existing instance is returned.

If (instance = null)

{

Instance = new Singleton ();

}

}

}

Return instance;

}

}

 

2. client code

Static void main (string [] ARGs)

{

Singleton singleton1 = singleton. getinstance ();

Singleton singleton2 = singleton. getinstance ();

If (singleton1 = singleton2)

{

Console. writeline ("instance singleton1 is the same as instance singleton2! ");

}

Console. ReadKey ();

}

3. instance running result

 

Iv. instance analysis (example) 1. Scenario

In the Mail sending mechanism, You need to Log the messages that have been sent. Only one process is allowed to operate the Txt file at a time. In this case, the singleton mode is suitable. Shows the structure.

 

WriteMailLog (string message) method: records the logs sent by Mail to a file.

_ Helper and _ fileLock: two static read-only process auxiliary objects are created when the program is running.

2. Code

1. 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 logs

/// </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 ("send Mail to smart life ...");

EmailLog w2 = EmailLog. GetInstance ();

W2.WriteEmailLog ("send Mail to James Hao ...");

}

3. instance running result

Summary)

This article briefly describes the Singleton Pattern concept and its design structure. It also describes a Mail-based LOG instance. The Singleton mode is commonly used. Simple design mode.

Related Article

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.