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达到客户端调用时候无需知道具体类型

  • 相关阅读:
    CopyOnWriteArrayList源码阅读笔记
    ArrayList源码阅读笔记
    MySQL和Oracle的区别
    思维导图概览SpringCloud
    Java学习之Request篇
    Java学习之servlet篇
    Java学习之数据库连接池
    Java学习之注解篇
    Java爬取先知论坛文章
    Java学习之爬虫篇
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2983410.html
Copyright © 2011-2022 走看看