static void Main(string[] args) { //BuilderExample(); //FactoryExample(); //FactoryMethodExample(); //FactoryMethodExample2(); //ProtoTypeExample();
SingletonExample();
//Console.WriteLine("Hello World!"); Console.ReadKey(); }
static void SingletonExample() { LazySingleton<SingletonData>.IsValueCreated(); Console.WriteLine("Name : {0} Age : {1}", LazySingleton<SingletonData>.Instance.Name, LazySingleton<SingletonData>.Instance.Age); LazySingleton<SingletonData>.IsValueCreated();
LazySingleton<SingletonData2>.IsValueCreated(); Console.WriteLine("Name : {0} Age : {1}", LazySingleton<SingletonData2>.Instance.Name, LazySingleton<SingletonData2>.Instance.Age); LazySingleton<SingletonData2>.IsValueCreated(); }
main.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.Singleton { public class SingletonData { public string Name { get; set; } public Int32 Age { get; set; }
public SingletonData() { Name = "Na"; Age = 34; } } }
SingletonData.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.Singleton { public class SingletonData2 { public string Name { get; set; } public Int32 Age { get; set; }
public SingletonData2() { Name = "Na2"; Age = 35; } } }
SingletonData2.cs |
using System; using System.Collections.Generic; using System.Text;
namespace DesignPatterns.Patterns.Singleton { public class LazySingleton<T> where T : new() { //초기화 모드 Thread publicationOnly private static readonly Lazy<T> instance = new Lazy<T>(() => new T(), System.Threading.LazyThreadSafetyMode.PublicationOnly); //일반 모드 Thread publicationOnly private static readonly Lazy<SingletonData> instance2 = new Lazy<SingletonData>(System.Threading.LazyThreadSafetyMode.PublicationOnly); public static T Instance { get { return instance.Value; } } private LazySingleton() { }
public static void IsValueCreated() { Console.WriteLine("IsValueCreated : {0}", instance.IsValueCreated); } } }
LazySingleton.cs |
'C# 디자인패턴' 카테고리의 다른 글
09# Bridge패턴 Structural Patterns (0) | 2019.05.29 |
---|---|
08# Adapter 패턴 Structural Patterns (0) | 2019.05.29 |
06# Prototype 패턴 Creational Patterns (0) | 2019.05.23 |
05# Factory Method 패턴2 Creational Patterns (0) | 2019.05.23 |
04# Factory Method 패턴1 Creational Patterns (0) | 2019.05.23 |