블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2731)
Unity3D (814)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (57)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (51)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
03-29 07:22

'Singleton'에 해당되는 글 7건

  1. 2014.03.24 Unity Singleton
  2. 2014.03.05 Generic Based Singleton for MonoBehaviours完全版(?)
  3. 2014.03.05 Singleton
  4. 2013.03.11 Unity Singleton
  5. 2010.10.22 C++/CLI Singleton
  6. 2010.07.02 C# 싱글톤
  7. 2010.07.02 Singleton

Unity Singleton

Unity3D/Script / 2014. 3. 24. 18:36
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    protected static bool m_bDontDestroyOnLoad = true;
    
    private static bool m_bApplicationQuit = false;
    private static object InstanceLocker = new object();

    private static T m_Instance = null;
    public static T Instance
    {
        get
        {
            if (true == m_bApplicationQuit)
                return null;

            lock (InstanceLocker)
            {
                // Instance requiered for the first time, we look for it
                if (null == m_Instance)
                {
                    T instance = GameObject.FindObjectOfType(typeof(T)) as T;

                    // Object not found, we create a temporary one
                    if (instance == null)
                    {
                        instance = new GameObject(typeof(T).ToString()).AddComponent<T>();

                        // Problem during the creation, this should not happen
                        if (instance == null)
                        {
                            Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                        }
                    }

                    if (instance != null)
                    {
                        Initialize(instance);
                    }
                }

                return m_Instance;
            }
        }
    }

    private static void Initialize(T instance)
    {
        if (m_Instance == null)
        {
            var startTime = System.DateTime.Now;
            m_Instance = instance;

            // 씬 전환 시, 삭제시킬 싱글톤은 부모 객체에 안붙이도록..
            // 싱글톤 시작 시, m_bDontDestroyOnLoad 셋팅 필요.
            if (true == m_bDontDestroyOnLoad)
            {
                GameObject goRoot = GameObject.Find("Singletons") as GameObject;
                if (null == goRoot)
                {
                    goRoot = new GameObject("Singletons");
                    // DontDestroyOnLoad() 등록은 하위 상속받는 쪽에서 하도록 하는 게 나을까?
                    DontDestroyOnLoad(goRoot);
                }
                m_Instance.transform.parent = goRoot.transform;
            }

            m_Instance.OnInitialize();
            var period = System.DateTime.Now - startTime;
            if (period.TotalSeconds > 1.0f)
            {
                var name = m_Instance.ToString();
                Debug.LogWarning("Profile Warnning. Singletion {" + name + "} too long init time : " 
                                 + period.TotalSeconds.ToString("F") + "Seconds");
            }
        }
        else if (m_Instance != instance)
        {
            DestroyImmediate(instance.gameObject);
        }
    }

    private static void Destroyed(T instance)
    {
        if (m_Instance == instance)
        {
            m_Instance.OnFinalize();
            m_Instance = null;
        }
    }

    public void CreateSingleton() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnInitialize() 호출 안됨.
    public virtual void OnInitialize() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnFinalize() 호출 안됨.
    public virtual void OnFinalize() { }
    protected virtual void CheckDontDestroyOnLoad() { }

    private void Awake()
    {
        Initialize(this as T);
    }

    void OnDestroy()
    {
        Destroyed(this as T);
    }

    private void OnApplicationQuit()
    {
        m_bApplicationQuit = true;
        Destroyed(this as T);
    }
}


반응형
Posted by blueasa
, |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using UnityEngine;
 
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    static T m_Instance = null;
 
    public static T instance
    {
        get
        {
            if( m_Instance != null )
            {
                return m_Instance;
            }
 
            System.Type type = typeof(T);
 
            T instance = GameObject.FindObjectOfType(type) as T;
 
            if( instance == null )
            {
                string typeName = type.ToString();
 
                GameObject gameObject = new GameObject( typeName, type );
                instance = gameObject.GetComponent<T>();
 
                if( instance == null )
                {
                    Debug.LogError("Problem during the creation of " + typeName,gameObject );
                }
            }
            else
            {
                Initialize(instance);
            }
            return m_Instance;
        }
    }
 
    static void Initialize(T instance)
    {
        if( m_Instance == null )
        {
            m_Instance = instance;
 
            m_Instance.OnInitialize();
        }
        else if( m_Instance != instance )
        {
            DestroyImmediate( instance.gameObject );
        }
    }
 
    static void Destroyed(T instance)
    {
        if( m_Instance == instance )
        {
            m_Instance.OnFinalize();
 
            m_Instance = null;
        }
    }
 
    public virtual void OnInitialize() {}
    public virtual void OnFinalize() {}
 
    void Awake()
    {
        Initialize( this as T );
    }
 
    void OnDestroy()
    {
        Destroyed( this as T );
    }
 
    void OnApplicationQuit()
    {
        Destroyed( this as T );
    }
}

使い方は

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using UnityEngine;
using System.Collections;
 
public class TestSingleton : MonoSingleton<TestSingleton>
{
    public override void OnInitialize()
    {
        Debug.Log ( "TestSingleton#OnInitialize" );
    }
 
    public override void OnFinalize()
    {
        Debug.Log ( "TestSingleton#OnFinalize" );
    }
}


출처 : http://caitsithware.com/wordpress/?p=118

반응형

'Unity3D > Script' 카테고리의 다른 글

Unity Singleton  (0) 2014.03.24
Platform Dependent Compilation  (0) 2014.03.11
Singleton  (0) 2014.03.05
Serializable, NonSerialized  (0) 2013.07.30
Get MAC address on Android device  (0) 2013.07.24
Posted by blueasa
, |

Singleton

Unity3D/Script / 2014. 3. 5. 10:41

일반형 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MySingleton
{
    private static MySingleton instance;
 
    //
    private MySingleton()
    {
 
    }
 
    static MySingleton()
    {
        instance = new MySingleton();
    }
 
    public static MySingleton Instance
    {
        get
        {
            return instance;
        }
    }
};

Component용 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using UnityEngine;
using System.Collections;
 
public class MySingleton : MonoBehaviour {
 
    private static MySingleton instance;
     
    //
    private MySingleton()
    {
    }
     
    //
    public static MySingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance =  FindObjectOfType(typeof (MySingleton)) as MySingleton;
             
                if (instance == null)
                {
                    GameObject obj = new GameObject("MySingleton");
                    instance = obj.AddComponent(typeof (MySingleton)) as MySingleton;
                    Debug.Log ("Could not locate an MySingleton object. MySingleton was Generated Automaticly.");
                }
            }
  
            return instance;
        }
    }
     
    void Awake()
    {
        DontDestroyOnLoad(this);
    }
     
    void OnApplicationQuit()
    {
        instance = null;
    }
}

제네릭 버전

일반형 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class  Singleton<T> where T : class, new()
{
    private static T instance;
         
    static Singleton()
    {
        instance = new T();
    }
     
    public static T Instance
    {
        get
        {
            return instance;
        }
    }
};

Component용 Singleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using UnityEngine;
using System.Collections;
  
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T instance;
     
    //
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance =  FindObjectOfType(typeof(T)) as T;
             
                if (instance == null)
                {
                    GameObject obj = new GameObject(typeof (T).ToString());
                    instance = obj.AddComponent(typeof (T)) as T;
                    instance.Init();
         
                    Debug.Log ("Could not locate an " + typeof (T).ToString() +" object. " + typeof (T).ToString() + " was Generated Automaticly.");
                }
            }
         
            return instance;
        }
    }
      
    void Awake()
    {
        if (instance == null)
        {
            instance = this as T;
            instance.Init();
        }
         
        DontDestroyOnLoad(this);
    }
      
    void OnApplicationQuit()
    {
        instance = null;
    }
     
    public virtual void Init()
    {
         
    }
}



반응형
Posted by blueasa
, |

Unity Singleton

Unity3D/Script / 2013. 3. 11. 10:58

Example :

GameMaster.cs

public class GameMaster : MonoSingleton< GameMaster >
{
    public int difficulty = 0;
    public override void Init(){ difficulty = 5; }
}

OtherClass.cs

You forgot a "using UnityEngine;" fixed. :P

using UnityEngine;
public class OtherClass: MonoBehaviour
{
    void Start(){ print( GameMaster.instance.difficulty ); } // 5
}

The code :

using UnityEngine;
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T m_Instance = null;
    public static T instance
    {
        get
        {
            // Instance requiered for the first time, we look for it
            if( m_Instance == null )
            {
                m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
 
                // Object not found, we create a temporary one
                if( m_Instance == null )
                {
                    Debug.LogWarning("No instance of " + typeof(T).ToString() + ", a temporary one is created.");
                    m_Instance = new GameObject("Temp Instance of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
 
                    // Problem during the creation, this should not happen
                    if( m_Instance == null )
                    {
                        Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                    }
                }
                m_Instance.Init();
            }
            return m_Instance;
        }
    }
    // If no other monobehaviour request the instance in an awake function
    // executing before this one, no need to search the object.
    private void Awake()
    {
        if( m_Instance == null )
        {
            m_Instance = this as T;
            m_Instance.Init();
        }
    }
 
    // This function is called when the instance is used the first time
    // Put all the initializations you need here, as you would do in Awake
    public virtual void Init(){}
 
    // Make sure the instance isn't referenced anymore when the user quit, just in case.
    private void OnApplicationQuit()
    {
        m_Instance = null;
    }
}


출처 : http://wiki.unity3d.com/index.php/Singleton

반응형
Posted by blueasa
, |

C++/CLI Singleton

Programming/C++/CLI / 2010. 10. 22. 16:12
public ref class MySingleton sealed
{
public:
	static MySingleton (void);
private: MySingleton (void);
public: static property MySingleton ^ mySingleton
{ MySingleton ^ get()
{ return m_mySingleton;
} } private: static MySingleton ^ m_mySingleton;
};

출처 : mine


ref class MyClass {
    // If you use a getter for 'instance' you can avoid 'initonly' keyword
    static MyClass^ instance = gcnew MyClass();

public:
    ...

    static property MyClass^ Instance
    {
        MyClass^ get()
        {
            return instance;
        }
    }
    ...
};

출처 : http://www.ureader.com/msg/14523461.aspx




반응형
Posted by blueasa
, |

C# 싱글톤

Programming/C# / 2010. 7. 2. 16:55

이 전략에서는 클래스의 임의 구성원을 처음으로 참조할 때에 인스턴스가 만들어집니다. 공용 언어 런타임이 변수 초기화를 담당합니다. 파생을 차단하기 위해 클래스가 sealed로 표시되며 이로 인해 인스턴스가 추가될 수 있습니다. 클래스를 sealed로 표시할 때의 장단점에 대한 설명은 [Sells03]을 참조하십시오. 또한 변수가 readonly로 표시됩니다. 이 표시는 정적 초기화 (여기서 표시된 것처럼) 중이나 클래스 생성자에서만 변수를 할당할 수 있음을 의미합니다. 여기서는 정적 초기화가 나타나 있습니다.

이 구현은 공용 언어 런타임을 사용하여 변수를 초기화한다는 점을 제외하면 앞의 예제와 유사합니다. 이 구현에서는 싱글톤(Singleton) 패턴이 해결하려고 하는 두 가지 문제 즉, 글로벌 액세스와 인스턴스화 제어에 대해 다룹니다. public static 속성은 인스턴스에 글로벌 액세스 포인트를 제공합니다. 또한 생성자가 private로 선언되기 때문에 클래스 외부에서는 싱글톤(Singleton) 클래스를 인스턴스화할 수 없습니다. 따라서 변수가 의미하는 것은 시스템에 존재할 수 있는 인스턴스만을 말합니다.

싱글톤(Singleton) 인스턴스는 private로 선언된 정적 구성원 변수에 의해 참조되므로 Instance 속성 호출이 클래스를 처음으로 참조한 후에야 비로소 인스턴스화가 수행됩니다. 따라서 이 솔루션은 싱글톤(Singleton)의 Design Patterns 양식에서처럼 지연 인스턴스화 속성 양식을 구현합니다.

이 방식의 유일한 단점은 인스턴스화 구성에 대한 제어가 약간 저하된다는 점입니다. Design Patterns 양식에서는 인스턴스화 이전에 비기본 생성자를 사용하거나 다른 작업을 수행할 수 있었습니다. 이 솔루션에서는 .NET Framework가 초기화를 수행하므로 이 옵션이 필요 없습니다. 대부분의 경우는 .NET에서 싱글톤(Singleton)을 구현하기 위해 정적 초기화가 더 선호됩니다.

멀티 스레드 싱글톤(Singleton)

대부분의 상황에는 정적 초기화가 적합합니다. 응용 프로그램이 인스턴스화를 연기해야 하고, 인스턴스화 이전에 비기본 생성자를 사용하거나 다른 작업을 수행해야 하고, 멀티 스레드 환경에서 작업해야 하는 경우는 다른 솔루션이 필요합니다. 하지만 정적 초기화 예제에서처럼 스레드 안정성을 보장하기 위해 공용 언어 런타임을 사용할 수 없는 경우가 존재합니다. 이러한 경우는 여러 개의 스레드에 대해 개체 인스턴스가 하나만 만들어지도록 특정한 언어 성능을 사용해야 합니다. 보다 더 일반적인 솔루션은 각각의 스레드가 싱글톤(Singleton) 인스턴스를 동시에 만들지 못하도록 막기 위해 이중 확인 잠금(Double-Check Locking)[Lea99] 관용구를 사용하는 것입니다.

참고:공용 언어 런타임은 다른 환경에서 흔히 나타나는 이중 확인 잠금(Double-Check Locking) 사용에 관련된 문제를 해결합니다. 이 문제에 대한 자세한 내용은 메릴랜드 주립대, 컴퓨터 사이언스 학과 웹 사이트(http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)에서 "The 'Double-Checked Locking Is Broken' Declaration" 을 참조하십시오.

다음 구현에서는 싱글톤(Singleton)의 인스턴스가 아직 만들어지지 않았을 때 한 개의 스레드만이 임계 영역(lock 블록에 의해 식별)에 들어갈 수 있습니다.

 

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
 

이 방식에서는 인스턴스가 필요할 경우에만 인스턴스가 단 한 개만 만들어지도록 합니다. 또한 인스턴스 변수에 액세스할 수 있기 전에 인스턴스 변수 할당을 완료하도록 변수를 volatile로 선언합니다. 마지막으로 이 방식에서는 교착 상태를 방지하기 위해 유형 자체를 잠그지 않고 syncRoot 인스턴스를 사용하여 잠급니다.

이 이중 확인 잠금(double-check locking) 방식은 Instance 속성 메서드의 모든 호출에 대한 독점적인 잠금을 막으면서도 스레드 동시 발생의 문제를 해결합니다. 이 방식에서는 또한 개체가 처음으로 액세스될 때까지는 인스턴스화를 연기할 수 있습니다. 실제로 응용 프로그램에는 이러한 유형의 구현이 거의 필요 없습니다. 대부분의 경우는 정적 초기화 방식만으로 충분합니다.

결과

C#에서 싱글톤(Singleton)을 구현할 경우 다음과 같은 이점과 단점이 있습니다.

이점

  • .NET Framework에서는 정적 변수 초기화가 언제 어떻게 일어나는지를 명시적으로 정의하므로 정적 초기화 방식이 가능합니다.

  • 위의 "멀티 스레드 싱글톤(Singleton)"에서 이미 설명한 이중 확인 잠금(Double-Check Locking) 관용구가 공용 언어 런타임에서 올바로 구현됩니다.

    단점

    멀티 스레드 응용 프로그램에 명시적 초기화가 필요한 경우는 스레딩 문제를 예방하기 위해 미리 조치를 취해야 합니다.

    참고 자료

    [Gamma95] Gamma, Helm, Johnson 및 Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.

    [Lea99] Lea, Doug. Concurrent Programming in Java, Second Edition. Addison-Wesley, 1999.

    [Sells03] Sells, Chris. "Sealed Sucks." sellsbrothers.com News. 다음 웹 사이트에서 구할 수 있습니다: http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=411

    참고: 제목과는 무관하게 "Sealed Sucks" 기사는 클래스를 sealed로 표시할 때의 장단점에 대해 실제로 설명합니다

    출처 : Tong - nicekiller77님의 C#통

  • 반응형
    Posted by blueasa
    , |

    Singleton

    Programming/C# / 2010. 7. 2. 16:53

    Definition

    Ensure a class has only one instance and provide a global point of access to it. 

    클래스는 오직 하나의 인스턴스만을 가질 수 있으며, 인스턴스에 접근할 수 있는 하나의 글로벌 포인터를 제공한다.

     

     UML Class Diagram

     

    Participants

    The classes and/or objects participating in this pattern are: Singleton   (LoadBalancer)

    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
    • responsible for creating and maintaining its own unique instance.

    이러한 패턴으로 클래스들과 객체들이 참여하는것을 싱글톤(Singleton)이라 한다.

    • 클라이언트들이 유일한 인스턴에 접근하는 하나의 인스턴스 연산을 정의한다. 인스턴스는 클래스 연산(Operation)이다.
    • 자신의 유일한 인스턴스를 생성하고 유지하는 것에 대해 신뢰할 수 있다.

     

    < 글/ 이미지지/ C# 소스 출처 : http://www.dofactory.com/ >

     

    Example

    Singleton 패턴은 객체의 인스턴스가 유일한 즉, 단 하나의 인스턴스만을 생성한다. 그리고 전연 변수와 같이 어디서든지 유일한 인스턴스에 접근하여 사용하는 패턴이다. 단 하나의 유일한 인스턴스만을 가지고 있어 중요한 자원을 관리하는 객체의 경우 편리하다.

    사실 그냥 전역 변수를 사용해서 관리하는 것도 좋지 않나 라고 생각도 했지만, 전역 변수를 사용하는 목적이 어디에서든 접근 가능하다는 목적도 있는 반면에 중요한 자원을 관리함에있어 인스턴스를 이용하여 자원을 관리를 한다. 그래서 그 인스턴스가 유일하다는 것을 보장해 줄 때 사용할 수 있다. 다른 예로, 실생활에서는 대통령은 하나이며 그 유일한 대통령에 의해 임무가 수행된다. 하지만, 대통령 즉, 인스턴스가 여러군대 생성된다면 이것은 혼란을 야기시킬것이다. 이러한 문제를 미리 방지 하고자 Singleton을 사용한다.

     

    Singleton은 기본적으로 다음과 같은 구조로 되어있다.

    1. public class Singleton
      {
           private static Singleton singleton;
           private Singleton()
           {         
           }
    2.  
    3.      public static Singleton getInstance()
           {
    4.  if(Singleton == null)
    5. singleton = new Singleton();
    6.           return singleton;
           }
      }

     

    위 코드에서 생성자를 보자. public이 아닌 private 로 선언되었다.  보통 Singleton ex = new Singleton() 으로 인스턴스로 생성하지만, 이렇게 여러 곳에서 인스턴스가 생성되는 것을 막기 위해 private 로 선언되었다.

    그래서 다음과 같이 이 인스턴스를 사용할 수 있다.

    1. Singleton ex = Singleton.GetInstance();

     

    Sample Code In C#, C++Singleton.zip <- Click Here


    출처 : http://blog.naver.com/fish19?Redirect=Log&logNo=120051709260

    반응형

    'Programming > C#' 카테고리의 다른 글

    Windows Forms FAQ - Windows Forms  (0) 2010.07.02
    C# 싱글톤  (0) 2010.07.02
    창크기 조절 막기  (0) 2010.07.02
    파일 드래그&드롭  (1) 2010.06.30
    Form-Form 데이터 전달  (0) 2010.06.29
    Posted by blueasa
    , |