--- tags: Design Pattern --- # Singleton ## define: Singleton可以輕鬆地保持一個類別只有一個實體,但常常因為輕鬆地就可以獲取其資料導致初學者過度濫用,我就是其中一個。 Singleton can easily keep a category with only one entity, but it is often overused by beginners due to the ease with which its data can be obtained, and I am one of them. <font color="#f00">advantage:</font> 1. From the beginning to the end of the application life cycle, it should be ensured that only one and the same instance (object) can be fetched <font color="#f00">disadvantage:</font> 1. The code has hidden dependencies in the invisible. Therefore, it will lead to tight coupling between categories 2. Unit testing will become more difficult, because the premise of unit testing will be loose coupling between categories, so that they can be unit tested independently 3. Since it is guaranteed that only one and the same instance can be obtained, under multi-threading, special attention needs to be paid to state changes. To minimize the impact on the application, the variation of the instance during execution should be minimal. --- ## time to use 當初在使用的時候並沒有單元測試的概念,所以透過Singleton宣告靜態變數用的很爽,但現在回來看雖然很方便使用卻會導致許多隱藏的bug,如多執行緒時的順序問題導致值不如預期等等,之後在使用這個東西時要慎用,甚至有工程師推薦不要使用。 When I was using it, there was no concept of unit testing, so it was very cool to declare static variables through Singleton, but now I look back and see that although it is very convenient to use, it will lead to many hidden bugs, such as the order problem when multiple threads are used, resulting in inferior values. Expect to wait, and then use this thing with caution, and even some engineers recommend not to use it. --- 別人的雙重鎖範例 reference: https://ithelp.ithome.com.tw/articles/10203092 ```cpp= public class Singleton { public static Singleton instance; private Singleton(){} public static Singleton getInstance(){ // 第一層判斷為了避免不必要的同步 if(instance == null){ synchronized (Singleton.class){ // 第二層判斷為了在null的狀況下建立實例 if(instance == null){ instance = new Singleton(); } } } return instance; } } ``` My relevant wrong code is in: https://github.com/andy091045/CryStole-2-/blob/master/Assets/Scripts/TestUI/CheckUserInput.cs reference: 1. https://ithelp.ithome.com.tw/articles/10221791 2. https://www.thinkinmd.com/post/2020/03/24/design-pattern-singleton/#i-5