zoukankan      html  css  js  c++  java
  • 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、运行效果

  • 相关阅读:
    简单理解Vue中的nextTick
    vue-router路由元信息及keep-alive组件级缓存
    Webpack配置区分开发环境和生产环境
    理解Vue.mixin,利用Vue.mixin正确的偷懒
    HTML5实现首页动态视频背景
    vue-router钩子函数实现路由守卫
    Vue路由(vue-router)详细讲解指南
    一文轻松搞懂Vuex
    利用HBuilder打包Vue开发的webapp为app
    WPF中剪贴板操作Clipboard
  • 原文地址:https://www.cnblogs.com/menglin2010/p/12079718.html
Copyright © 2011-2022 走看看