聊聊C#中的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就可以了,这样的代码方便扩展也方便维护,毕竟功能逻辑都在父类里面。
 
不过仔细想想,这样的代码还是有点问题,类继承意味着子类应该是父类的特化,但是我们这几个Manager类怎么看也不是SingletonHolder的特化,如果一定要说,它们应该是引擎模块(ModuleManager)的一种特化。所以让它们继承自SingletonHolder其实不是最好的方法,虽然语法正确、行为正确但是并不是语义正确,作为程序员,我们应该追求尽善尽美。而且未来真会有抽象出一个父类ModuleManager的可能,到时候就发现唯一的类继承名额已经给SingletonHolder给占用了,所以我们需要寻找一种既能注入逻辑代码,又不涉及类继承的方法。
 

轮到Mixin出场

什么是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[5] (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是面向对象编程语言中的一种概念,允许程序员以在类继承之外的方式为类添加一些方法。Mixin的本意是冰淇淋面上的那些小点缀比如巧克力、草莓、葡萄干等。这些小点缀既能添加冰淇淋的风味也不会改变冰淇淋的内部状态——毕竟冰淇淋无论如何不会继承自巧克力、草莓和葡萄干,对吧,这种概念正是我们需要的。
 

Mixin在C#中的应用

从上面的描述可以看出,Mixin的宗旨就是不破坏对象但是又能提供额外一些功能,它们通常以拥有实现的接口出现(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
    }

这样任何想实现单例的类,只要让它实现ISingleton接口即可,因为这个接口是空接口,所以实现它不会对类造成任何负担,同时这种接口实现也不会出现之前的继承问题,这就是Mixin的妙用。

 

从C#8.0开始

从C#8.0开始,接口可以有方法的默认实现(包括static method),我们可以更加简单的实现Mixin解决之前的问题

	interface SingletonHolder<T>
        where T:class
    {
        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这种基于接口的代码逻辑注入也许能有奇效哦!如果大家有什么看法或者建议,欢迎留言讨论!
创作不易,还请关注!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值