溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#中的Mixin怎么使用

發(fā)布時間:2022-05-30 09:38:20 來源:億速云 閱讀:144 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“C#中的Mixin怎么使用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“C#中的Mixin怎么使用”文章能幫助大家解決問題。

    從一個簡單例子說起

    試想我們在寫一個游戲引擎,創(chuàng)建如下類:

        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類分別控制腳本、實體和動畫。但是我們突然發(fā)現,這三個類應該都是單例才合適。按照我們之前在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
        }

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

    在父類中實現單例

    很容易就能想到,既然這塊代碼邏輯都是一樣的,我們?yōu)槭裁床话阉釤挼礁割??像這樣

        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,到時候就發(fā)現唯一的類繼承名額已經給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>{}

    關于“C#中的Mixin怎么使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識,可以關注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI