zoukankan      html  css  js  c++  java
  • 构造注入

    这种方式就是在构造函数时候注入类型

    直接看例子

     public interface ITimeProvider
        {
            DateTime CurrentDate { get; }
        }
    
        public class TimeProvider : ITimeProvider
        {
            public DateTime CurrentDate { get { return DateTime.Now; } }
        }
    
        public class Assembler
        {
            static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();
            static Assembler()
            {
                dictionary.Add(typeof(ITimeProvider), typeof(TimeProvider));
            }
    
            public object Creat(Type type)
            {
                if ((type == null) || !dictionary.ContainsKey(type))
                    throw new NullReferenceException();
                return Activator.CreateInstance(dictionary[type]);
            }
    
            //泛型方式调用
            public T Creat<T>()
            {
                return (T)Creat(typeof(T));
            }
        }

    下面看构造注入类

     public class Client
        {
            ITimeProvider timeProvider;
            public Client(ITimeProvider timeProvider)
            {
                this.timeProvider = timeProvider;
            }
        }

    那么客户端调用时候

            [TestMethod()]
            public void ClientConstructorTest()
            {
                ITimeProvider timeProvider = (new Assembler()).Creat<ITimeProvider>();
                Assert.IsNotNull(timeProvider);
                Client target = new Client(timeProvider);
            }

    这样又一次依赖Assembler达到客户端调用时候无需知道具体类型

  • 相关阅读:
    个人作业——软件产品案例分析
    软件工程结对作业二
    软件工程团队展示
    软件工程第三次作业
    软件工程实践第二次作业
    软件工程实践第一次作业
    第八次课程作业
    第五次课程作业
    第四次课程作业
    wind本地MySQL数据到hive的指定路径
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2983410.html
Copyright © 2011-2022 走看看