1、手写Unity容器--极致简陋版Unity容器

思路:

1、注册类型:把类型完整名称作为key添加到数据字典中,类型添加到数据字典的value中

2、获取实例:根据完整类型名称也就是key取出value,用反射创建类型的实例

1、IPhone接口

namespace SimplestUnity
{
    interface IPhone
    {
        void Call();
    }
}

2、AndroidPhone实现

namespace SimplestUnity
{
    public class AndroidPhone:IPhone
    {
        public AndroidPhone()
        {
            Console.WriteLine("{0}构造函数", this.GetType().Name);
        }

        public void Call()
        {
            Console.WriteLine("{0}打电话", this.GetType().Name);
        }
    }
}

3、容器--接口

namespace SimplestUnity
{
    public interface IDaivdContainer
    {
        void RegisterType<TFrom, TTo>();

        T Resolve<T>();
    }
}

4、容器--实现

namespace SimplestUnity
{
    public class DaivdContainer:IDaivdContainer
    {
        private Dictionary<string, Type> containerDictionary = new Dictionary<string, Type>();//字典

        public void RegisterType<TFrom, TTo>()
        {
            containerDictionary.Add(typeof(TFrom).FullName, typeof(TTo));
        }

        public T Resolve<T>()
        {
            Type type = containerDictionary[typeof(T).FullName];
            return (T)Activator.CreateInstance(type);
        }
    }
}

5、调用

class Program
{
        static void Main(string[] args)
        {
            DaivdContainer davidContainer = new DaivdContainer();
            davidContainer.RegisterType<IPhone, AndroidPhone>();
            IPhone iphone = davidContainer.Resolve<IPhone>();
iphone.Call(); } }

猜你喜欢

转载自www.cnblogs.com/menglin2010/p/12079718.html