装饰器接口

    public interface IDecorator
    {
        string DecoratorAction();
    }

被装饰的类

    [StopRing]
    [MetalimBeam]
    [PunchLaser]
    public class Ultraman : IDecorator
    {
        private string name;
        public Ultraman(string name)
        {
            this.name = name;
        }

        public string DecoratorAction()
        {
            return name;
        }
    }

装饰类的基类

    [AttributeUsage(AttributeTargets.Class)]
    public abstract class BeamAttribute : Attribute, IDecorator
    {

        protected IDecorator decorator;
        public BeamAttribute()
        {

        }

        public void SetDecorator(IDecorator decorator)
        {
            this.decorator = decorator;
        }

        public abstract string DecoratorAction();
    }

第一个装饰类

    public class StopRing : BeamAttribute
    {
        public override string DecoratorAction()
        {
            return decorator.DecoratorAction() + " 止动环";
        }
    }

第二个装饰类

    public class MetalimBeam : BeamAttribute
    {
        public override string DecoratorAction()
        {
            return decorator.DecoratorAction() + "  美塔林光线";
        }
    }

第三个装饰类

    public class PunchLaser : BeamAttribute
    {
        public override string DecoratorAction()
        {
            return decorator.DecoratorAction() + " 普拉斯光线";
        }
    }

装饰类工厂

public class DecoratorFactory
    {
        public static IDecorator GetUltraman(string name)
        {
            Ultraman ultraman = new Ultraman(name);
            return SetUltramanBeam(ultraman);
        }

        private static IDecorator SetUltramanBeam(Ultraman ultraman)
        {
            Type type = typeof(Ultraman);
            var beams = type.GetCustomAttributes(false);
            IDecorator foreBeam = null;
            foreach ( var beam in beams )
            {
                BeamAttribute currentBeam = beam as BeamAttribute; 
                if (foreBeam == null ) {
                    currentBeam.SetDecorator(ultraman);
                }
                else
                {
                    currentBeam.SetDecorator(foreBeam);
                }
                foreBeam = currentBeam;
            }
            return foreBeam;
        }
    }

program启动

    internal class Program
    {
        static void Main(string[] args)
        {
            
            var aa = DecoratorFactory.GetUltraman("ace").DecoratorAction();

        }
    }

 

posted on   HRDK  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义



点击右上角即可分享
微信分享提示