属性注入

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

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

posted on 2013-03-27 13:19  HOT SUMMER  阅读(201)  评论(0编辑  收藏  举报

导航