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

模拟Unity容器实例化AndroidPhone

一、条件
1、容器--工厂
2、集合
3、反射
4、特性--相当于配置

二、思路

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(); } }

6、运行效果

原文地址:https://www.cnblogs.com/menglin2010/p/12079718.html