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

    自定义特性

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

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

  • 相关阅读:
    4.状态简览
    3.获取git仓库
    2.获取帮助
    1.初次运行git前的配置
    linux命令总结
    使用github参与到开源项目的维护
    mongodb远程连接
    springmvc/springboot处理前台字符串日期自动转换成后台date类型的三种办法
    事务明明配置没有问题,出错时却不执行回滚
    tmux 安装
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2984392.html
Copyright © 2011-2022 走看看