Singleton in Csharp
using System;
namespace DoFactory.GangOfFour.Singleton.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Singleton Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
//Constructor is protected — cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
// Test for same instance
if (s1 == s2)
{
Console.WriteLine(“Objects are the same instance”);
}
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The ‘Singleton’ class
/// </summary>
class Singleton
{
private static Singleton _instance;
//Constructor is ‘protected’
protected Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is not thread safe.
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public void demo()
{
throw new System.NotImplementedException();
}
}
}
Singleton Design Pattern
Singleton Design Pattern
Mục đích
Mẫu singleton đảm bảo một lớp chỉ có một cà đặt duy nhất và cung cấp một điểm truy cập mở để truy cập tới nó.
UML class Diagram
Áp dụng
Các lớp hoặc các đối tượng tham gia mô hình này:
Singleton
- Định nghĩa một “Instance operation” mà client truy cập đến là duy nhất. Khởi tạo là một opetation của lớp
- Chịu trách nhiệm về việc khởi tạo và duy trì sử khởi tạo duy nhất của nó
Code mẫu:
Design Patterns
In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
Thử chút
Thửu mới biết chứ
Hello world!
Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!