• 属性注入


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

    自定义特性

    [AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]
        sealed class DecoratorAttribute : Attribute
        {
            public readonly object injector;
            readonly Type type;
            public DecoratorAttribute(Type type)
            {
                if (type == null) throw new ArgumentNullException("type");
                this.type = type;
                injector = (new Assembler()).Creat(this.type);
            }
            public Type Type { get { return this.type; } }
        }

    对Assembler再包装

     static class AttributeHelper
        {
            public static T Injector<T>(object target) where T:class
            {
                if (target == null) throw new ArgumentNullException("target");
                return (T)(((DecoratorAttribute[])target.GetType().GetCustomAttributes(typeof(DecoratorAttribute), false))
                    .Where(x => x.Type == typeof(T))
                    .FirstOrDefault()
                    .injector);
            }
        }

    实体类

     [Decorator(typeof(ITimeProvider))]
        class Client
        {
            public int GetYear()
            {
                var provider = AttributeHelper.Injector<ITimeProvider>(this);
                return provider.CurrentDate.Year;
            }
        }

    看看调用

            /// <summary>
            ///GetYear 的测试
            ///</summary>
            [TestMethod()]
            public void GetYearTest()
            {
                Client target = new Client(); // TODO: 初始化为适当的值
                target.GetType();
            }

    这里有点模糊,我自己手动打出来这个段代码并且测试通过,但是却不懂在什么场合去应用他,后面我会把自己做过的几个软件从新按照设计模式规划下,到时如果用到会对这里做个说明,现在先朦朦胧胧的放在这里,待后续

  • 相关阅读:
    TO DO
    Ethernet、IP、TCP、UDP、ARP数据格式与封装解封
    Django documentation重点段落
    Docker、Docker Compose内容汇总
    systrace
    超级无敌傻瓜教程系列之 GraphQL教程
    Java常用lambda表达式
    MySQL索引与数据页的关系
    wireshark抓包127.0.0.1/本地
    OpenAL采集手动修改默认设备问题
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2984392.html
Copyright © 2020-2023  润新知