日本語
こんばんは!
Advent Calendar 2024の6日目投稿をしていきます。
今回はC#についての記事で、シングルトンというデザインパターンについて投稿していきます!
シングルトンとは
シングルトン(Singleton)パターンは、特定のクラスのインスタンスがアプリケーション全体でただ1つだけであることを保証し、その唯一のインスタンスにアクセスする方法を提供します。
このパターンは、グローバルな設定、ログ記録、キャッシュ管理など、状態を1つだけ管理したい場合に役立ちます。
目的
特定のクラスに1つのインスタンスだけを許容し、全体で共有できるようにする。
利点
インスタンスの重複作成を防ぐ。
状態を一元管理できる。
実装例
public sealed class LazySingleton
{
private static readonly Lazy<LazySingleton> _instance =
new Lazy<LazySingleton>(() => new LazySingleton());
public static LazySingleton Instance => _instance.Value;
private LazySingleton()
{
Console.WriteLine("Lazy Singleton instance created.");
}
}
//使用例
class Program
{
static void Main(string[] args)
{
LazySingleton instance1 = LazySingleton.Instance;
LazySingleton instance2 = LazySingleton.Instance;
Console.WriteLine(ReferenceEquals(instance1, instance2)); // 出力: True
}
}
上のコードは最初のインスタンス呼び出し時のみ、「"Lazy Singleton instance created."」を出力し、2回目の読み出し時は、インスタンスが使いまわされているのコンストラクタは使用されず、「"Lazy Singleton instance created."」は出力されない仕組みになっています。
グローバル的なクラスと考えていいでしょう!
とても面白いですね♪
ここまで読んでいただきありがとうございます!
ENGLISH
Good evening!
I will be posting day 6 of the Advent Calendar 2024.
This time, I will be posting about C# and a design pattern called Singleton!
What is Singleton?
The Singleton pattern ensures that there is only one instance of a particular class in the entire application and provides a way to access that sole instance.
This pattern is useful for global configuration, logging, cache management, and other situations where you want to manage only one piece of state.
Purpose
Allow only one instance of a particular class to be shared across the board.
Advantages
Prevents duplicate instance creation.
Centralized management of status is possible.
Implementation example
public sealed class LazySingleton
{
private static readonly Lazy<LazySingleton> _instance =
new Lazy<LazySingleton>(() => new LazySingleton());
public static LazySingleton Instance => _instance.Value;
private LazySingleton()
{
Console.WriteLine("Lazy Singleton instance created.");
}
}
//example
class Program
{
static void Main(string[] args)
{
LazySingleton instance1 = LazySingleton.Instance;
LazySingleton instance2 = LazySingleton.Instance;
Console.WriteLine(ReferenceEquals(instance1, instance2)); // 出力: True
}
}
The above code outputs “”Lazy Singleton instance created.“” only at the first instance invocation, and at the second read, the constructor is not used because the instance is used repeatedly, and “”Lazy Singleton instance created.
You can think of it as a global class!
Very interesting... ♪
Thank you for reading this far!