设计模式のDecoratorPattern(装饰器模式)----结构模式

一、产生背景

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

二、一般做法

假设有一部手机你购买来以后只有手机,然后你需要再给其添加一些装饰,比如保护壳,钢化膜或者手机贴画等,这个就是装饰者模式的思想

装饰器模式主要组成部分:

Component:定义一个对象接口,可以给这些对象动态地添加职责

ConcreteComponent:定义一个对象,可以给这个对象添加一些职责

Decorator:维持一个指向Component的指针,并定义一个与Component接口一致的接口

ConcreteDecorator:负责向ConcreteComponent添加功能

在装饰模式中,Decorator定义了一个装饰接口类。因为Decorator与ConcreteComponent继承同一个接口,所以继承Decorator的类ConcreteDecorator可以使用ConcreteComponent的方法,再在ConcreteDecorator里面加入一些新的方法,也就是装饰,就成为了一个包装好的装饰类。

三、实例

1、抽象基类

public abstract class ProductBase
{
    public abstract string GetName();
    public abstract double GetPrice();
}

2、具体产品

 public class ConcretProuct : ProductBase
    {
        private string _name;
        private double _price;
        public ConcretProuct(string name, double price)
        {
            this._name = name;
            this._price = price;
        }
        public override string GetName()
        {
            return _name;
        }
        public override double GetPrice()
        {
            return _price;
        }
    }

3、装饰

    public class Decorator : ProductBase
    {
        private ProductBase _product = null;
        private string _name;
        private double _price;
        public Decorator(ProductBase product, string name, double price)
        {
            this._product = product;
            this._name = name;
            this._price = price;
        }
        public override string GetName()
        {
            return string.Format("{0},{1}", _product.GetName(), _name);
        }
        public override double GetPrice()
        {
            return _product.GetPrice() + _price;
        }
    }

四、设计模式分析

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

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

使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。

注意事项:可代替继承。

原文地址:https://www.cnblogs.com/xietianjiao/p/8509757.html