装饰器模式 动态组合装饰

DesignPartten_Decoration_Dynamic_Composition

先定义个一个形状的接口,可以转换为字符串

interface IShape
    {
       string AsString();
    }

添加各种形状

 class Circel:IShape
    {
        float ridus;

        public Circel(float ridus)
        {
            this.ridus = ridus;
        }

        public string AsString()
        {
            return $"Circle Ridus:{ridus}";
        }

        public void Resize(float size)
        {
            ridus *= size;
        }
    }

    class Square :IShape
    {
        float Side;

        public Square(float side)
        {
            Side = side;
        }

        public string AsString()
        {
           return $"Square Side: {Side}" ;
        }
    }

开始装饰:

class ColorShape : IShape
    {
        IShape shape;
        string color;

        public ColorShape(IShape shape, string color)
        {
            this.shape = shape;
            this.color = color;
        }

        public string AsString()
        {
           return $"{shape.AsString()} Color :{color}";
        }
    }

    class Transparent:IShape
    {
        IShape shape;
        float percentage;

        public Transparent(IShape shape, float _percentage)
        {
            this.shape = shape;
            this.percentage = _percentage;
        }

        public string AsString()
        {
            return $"{shape.AsString()} Transparent:{percentage*100.0}%";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Square sq = new Square(1.23f);
            Console.WriteLine(sq.AsString());

            ColorShape colorShape = new ColorShape(sq, "Black");
            Console.WriteLine(colorShape.AsString());

            Transparent transparent = new Transparent(colorShape, 0.5f);
            Console.WriteLine(transparent.AsString()); 
        }
    }

运行时调用

 

posted @ 2022-05-18 15:19  后跳  阅读(11)  评论(0编辑  收藏  举报