C# 设计模式 结构型模式 之 装饰器模式

装饰器模式 允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

使用:在不想增加很多子类的情况下扩展类。

下面实例演示装饰器模式的用法。其中,把一个形状装饰上不同的颜色,同时又不改变形状类。

namespace 装饰器模式
{
    internal class Program
    {
        static void Main(string[] args)
        {
            EmbellishShape redCircle = new RealizeEmbellishShape(new Circle());
            redCircle.Draw();
            /*
             * 控制台:
             画了一个圆
             设置图形的边框为红色
             */
        }
    }
    public interface Shape
    {
        void Draw();
    }
    public class Circle : Shape
    {
        public void Draw()
        {
            Console.WriteLine("画了一个圆");
        }
    }
    public class Rectangle : Shape
    {
        public void Draw()
        {
            Console.WriteLine("画了一个长方形");
        }
    }
    //实现了 Shape 接口的抽象装饰类
    public abstract class EmbellishShape
    {
        protected Shape shape;
        public EmbellishShape(Shape shape)
        {
            this.shape = shape;
        }
        public virtual void Draw()
        {
            shape.Draw();
        }
    }
    //扩展了 EmbellishShape 类的实体装饰类。
    public class RealizeEmbellishShape : EmbellishShape
    {
        public RealizeEmbellishShape(Shape shape) : base(shape)
        {

        }
        public override void Draw()
        {
            base.shape.Draw();
            SetRedBorder(base.shape);
        }
        private void SetRedBorder(Shape shape)
        {
            Console.WriteLine("设置图形的边框为红色");
        }
    }
}

 缺点:多层装饰比较复杂。

猜你喜欢

转载自blog.csdn.net/q8812345qaz/article/details/127591112
今日推荐