设计模式学习笔记-装饰者模式

装饰者模式

作为一个程序员在做程序开发得过程中最烦得莫过于需求更改后对原来代码得更改。这其中带来得问题有可能远远超过需要更改得问题个数。所以如果做到“不更改,只扩展”将会带来直观的改变。而装饰者模式就是解决这个问题的比较实用得一种模式。

装饰者模式:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。动态地将责任附加到对象上,想要扩展功能,装饰者提供有利于继承的另一种选择。

UML图


类图不太好容易理解,下面给出一个小的简单得列子:

超类Component

 public abstract class Beverage
    {
        protected string description = "Unknown Beverage";
        public virtual  string getDescription() { return description; }
        public abstract double cost();
    }
      需要被装饰的类concreteComponent

public class Espresso:Beverage
    {
        public Espresso()
        {
            description = "Espresso";
        }
        public override double cost() { return 1.99; }
    }
      装饰者调料父类Decorator
public abstract class CondimentDecorator:Beverage
    {
        protected Beverage beverage;
        public override string getDescription()
        {
            return beverage.getDescription() +","+ description;
        }
    }
    其中得一个调料concreteComponentA
public class Mocha : CondimentDecorator
    {
        public Mocha(Beverage beverageTemp)
        {
            beverage = beverageTemp;
            description = "Mocha";
        }
        public override double cost()
        {
            return beverage.cost() + 0.2;
        }
    }
    最后的使用

 Beverage espresso = new Espresso();
            MessageBox.Show(espresso.getDescription()+" 的咖啡价钱为:"+espresso.cost().ToString());

            Beverage espressoTemp = new Espresso();
            espressoTemp = new Mocha(espressoTemp);
            espressoTemp = new Mocha(espressoTemp);
            MessageBox.Show(espressoTemp.getDescription() + " 的咖啡价钱为:" + espressoTemp.cost().ToString());

在其中你可以添加很多中调味料,以及咖啡。


个人感悟:

在使用装饰者模式得时候一定要抽出里面得变化然后进行抽象。至于里面得变化需要具体问题具体分析。抽取变化得时候没有啥好办法就是要多多练习,积累经验。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值