본문 바로가기
C# 디자인패턴

07# Singleton 패턴(thread safe) Creational Patterns

by NaHyungMin 2019. 5. 24.

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