聊聊C#中的Mixin

寫在前面

Mixin本意是指冰淇淋表面加的那些草莓醬,葡萄乾等點綴物,它們負責給冰淇淋添加風味。在OOP裏面也有Mixin這個概念,和它的本意相似,OOP裏面的Mixin意在爲類提供一些額外功能——在不破壞類本身或者它的繼承鏈的基礎上,在某些情況下可能會起到妙用。今天跟着老胡一起來看看吧。
 

從一個簡單例子說起

試想我們在寫一個遊戲引擎,創建如下類:

    class ScriptManager
    {
        public void AddScript(){/*省略實現*/}

        public void RemoveScript(){/*省略實現*/}
    }

    class EntityManager
    {
        public void AddEntity() {/*省略實現*/}

        public void RemoveEntity() {/*省略實現*/}
    }

    class AnimationManager
    {
        public void AddAnimationToWorld() {/*省略實現*/}

        public void RemoveAnimationFromWorld() {/*省略實現*/}
    }

代碼非常簡單,三個manager類分別控制腳本、實體和動畫。但是我們突然發現,這三個類應該都是單例才合適。按照我們之前在C#中的Singleton中介紹的方法,我們這麼改寫一下這三個類。
 

在類中實現單例

最簡單的,我們可以這麼改

    class ScriptManager
    {
        private static ScriptManager _instance = null;
        public static ScriptManager Instance
        {
            get
            {
                if(_instance == null)
                {
                    lock(typeof(ScriptManager))
                    {
                        if(_instance == null)
                        {
                            _instance = new ScriptManager();
                        }
                    }
                }
                return _instance;
            }
        }
        public void AddScript(){/*省略實現*/}

        public void RemoveScript(){/*省略實現*/}
        private ScriptManager() {/*省略實現*/} //車門焊死,不讓外部調用
    }

	class EntityManager
	{
		//類似的修改方法
	}
	
	class AnimationManager
	{
		//類似的修改方法
	}

    static void Main(string[] args)
    {
        var instance1 = ScriptManager.Instance;
        var instance2 = ScriptManager.Instance;
        var result = instance1 == instance2; //true
    }

看起來沒有什麼問題,確實也滿足了可用的要求,但是僅僅可用是不夠的,我們想要更好的解決方案,而且這種修改方法雖然簡單,但如果我們想要修改的類不止這三個,或者,我們想要添加的不僅僅是單例方法,我們需要寫的代碼會成倍增加,所以我們想要更好的解決方案。
 

在父類中實現單例

很容易就能想到,既然這塊代碼邏輯都是一樣的,我們爲什麼不把它提煉到父類?像這樣

    class SingletonHolder<T>
        where T : class
    {
        private static T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (typeof(T))
                    {
                        if (_instance == null)
                        {
                            _instance = (T)Activator.CreateInstance(typeof(T), true); //調用非公有構造器
                        }
                    }
                }
                return _instance;
            }
        }
    }
    
    class ScriptManager : SingletonHolder<ScriptManager>
    {
		//省略
    }

    class EntityManager : SingletonHolder<EntityManager>
    {
		//省略
    }

    class AnimationManager : SingletonHolder<AnimationManager>
    {
		//省略
    }

    static void Main(string[] args)
    {
        var ScriptManager1 = ScriptManager.Instance;
        var ScriptManager2 = ScriptManager.Instance;
        var result = ScriptManager1 == ScriptManager2; //true

        var EntityManager1 = EntityManager.Instance;
        var EntityManager2 = EntityManager.Instance;
        result = EntityManager1 == EntityManager2; //true

        var AnimationManager1 = AnimationManager.Instance;
        var AnimationManager2 = AnimationManager.Instance;
        result = AnimationManager1 == AnimationManager2; //true
    }

確實可以,這樣就算有再多的類需要實現單例,只要讓它們繼承SingletonHolder就可以了,這樣的代碼方便擴展也方便維護,畢竟功能邏輯都在父類裏面。
 
不過仔細想想,這樣的代碼還是有點問題,類繼承意味着子類應該是父類的特化,代表着一種is-a的關係,但是我們這幾個Manager類和SingletonHolder並不是這種關係,它們和SingletonHolder更多像是一種實現契約的關係;如果一定要說is-a,它們應該是引擎模塊(ModuleManager)的一種特化。所以讓它們繼承自SingletonHolder其實不是最好的方法,雖然語法正確、行爲正確但是並不是語義正確,作爲程序員,我們應該追求盡善盡美。而且未來真有可能會抽象出一個父類ModuleManager,到時候就發現唯一的類繼承名額已經給SingletonHolder給佔用了,所以我們需要尋找一種既能注入邏輯代碼,又不涉及類繼承的方法。
 

輪到Mixin出場

定義

In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".
Mixins encourage code reuse and can be used to avoid the inheritance ambiguity that multiple inheritance can cause (the "diamond problem"), or to work around lack of support for multiple inheritance in a language. A mixin can also be viewed as an interface with implemented methods. This pattern is an example of enforcing the dependency inversion principle.

這是在Wiki上面Mixin的定義,允許程序員以在類繼承之外的方式爲類添加一些方法,即,既能爲類提供方法實現,又可以避免成爲類的父類,避免了類繼承和多重繼承所帶來的問題,這種概念正是我們需要的。
 

Mixin在C#中

在C#中,它們通常以擁有實現的接口出現(default implementation interface from C#8.0),而在C#8.0之前,我們通常以輔助類的方式來實現Mixin,我們下面以這兩種方式改寫之前的類。
 

在8.0之前

我們定義出一個接口,然後在外部基於這個接口實現單例邏輯(不用擴展方法是因爲擴展方法不支持static method,如果想要注入的是非static method可以使用基於接口的擴展方法)

    class SingletonHolder<T>
        where T : class, ISingleton
    {
        private static T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (typeof(T))
                    {
                        if (_instance == null)
                        {
                            _instance = (T)Activator.CreateInstance(typeof(T), true);
                        }
                    }
                }
                return _instance;
            }
        }
    }

    interface ISingleton
    {
        //沒有任何方法因爲只是一個標記
    }

    class ScriptManager : ISingleton
    {
        private ScriptManager() {/*省略實現*/}
        public void AddScript(){/*省略實現*/}

        public void RemoveScript(){/*省略實現*/}
    }

    class EntityManager : ISingleton
    {
        private EntityManager() {/*省略實現*/}
        public void AddEntity() {/*省略實現*/}

        public void RemoveEntity() {/*省略實現*/}
    }

    class AnimationManager : ISingleton
    {
        private AnimationManager() {/*省略實現*/}
        public void AddAnimationToWorld() {/*省略實現*/}

        public void RemoveAnimationFromWorld() {/*省略實現*/}
    }

    static void Main(string[] args)
    {
        var ScriptManager1 = SingletonHolder<ScriptManager>.Instance;
        var ScriptManager2 = SingletonHolder<ScriptManager>.Instance;
        var result = ScriptManager1 == ScriptManager2; //true

        var EntityManager1 = SingletonHolder<EntityManager>.Instance;
        var EntityManager2 = SingletonHolder<EntityManager>.Instance;
        result = EntityManager1 == EntityManager2; //true

        var AnimationManager1 = SingletonHolder<AnimationManager>.Instance;
        var AnimationManager2 = SingletonHolder<AnimationManager>.Instance;
        result = AnimationManager1 == AnimationManager2; //true
    }

這就是Mixin的用處,看起來這種實現方式的好處有:

  • 類只需要聲明實現ISingleton即可完成單例相關編碼
  • ISingleton是接口,類可以聲明實現多個接口而不會有類繼承的單一限制,同時也不會有那種is-a的類繼承煩惱
  • ISingleton是空接口,任何類實現它不需要額外的對該類自身的修改,就像淋上草莓醬不會對冰淇淋本身造成影響一樣,符合開閉原則
     
從C#8.0開始

從C#8.0開始,接口可以有方法的默認實現(包括static method),我們可以更加簡單的實現Mixin解決之前的問題

    interface SingletonHolder<T>
        where T:class
    {
        private static T _instance = null;
        static T Instance
        {
            get
            {
                if(_instance == null)
                {
                    lock(typeof(T))
                    {
                        if(_instance == null)
                        {
                            _instance = (T)Activator.CreateInstance(typeof(T), true);
                        }
                    }
                }
                return _instance;
            }
        }
    }
    class ScriptManager : SingletonHolder<ScriptManager>{}
    class EntityManager : SingletonHolder<EntityManager>{}
    class AnimationManager : SingletonHolder<AnimationManager>{}

這就是Mixin以及它在C#中的簡單使用方法,希望通過這篇介紹能讓大家對這種用法有所瞭解,在想要給類添加代碼邏輯但是又不想改變類內部或者影響類的繼承體系的時候,使用Mixin這種基於接口的代碼邏輯注入也許能有奇效哦!如果大家有什麼看法或者建議,歡迎留言討論。
創作不易,還請關注!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章