头先设计模式-使用Starbuzz的装饰器模式 [英] Head First Design Patterns - Decorator Pattern using Starbuzz

查看:69
本文介绍了头先设计模式-使用Starbuzz的装饰器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《 Head First Design Patterns》一书,并专门研究 Decorator 模式的Starbuzz示例。

I am going through the book Head First Design Patterns and am specifically looking at the Starbuzz example for the Decorator pattern.

我很难理解提供的示例中对 CondimentDecorator 的确切需求是什么。为什么 Mocha 不能简单地扩展饮料

I am having trouble understanding that what exactly is the need for CondimentDecorator in the example provided. Why can't Mocha simply extend Beverage? What's the need for another layer of abstraction?`

public abstract class Beverage  
{  
   String description = "Unknown beverage";

    public String getDescription()
   {
     return description; 
   }

   public abstract double cost();  
}  

public abstract class CondimentDecorator extends Beverage  
{  
    public abstract String getDescription();
}  

public class Mocha extends CondimentDecorator
{  
   Beverage b;

   public Mocha(Beverage b)
   {
     this.b=b;
   }

   public String getDescription()
   {
      return b.getDescription() + ", Mocha";
   }

   public double cost()
   {
     return .20 + b.cost();
   }
}


推荐答案

,在您发布的示例中还不清楚,但是抽象类通常负责组件封装,默认方法实现是将方法调用委托给该组件。

Well, in the sample you posted it isin't that clear, but the abstract class usually takes care of the component encapsulation and the default method implementations are to delegate method calls to that component.

因此,在实现混凝土装饰器时,如果不需要,您不必重写所有方法。

Therefore, when implementing concrete decorators, you would't have to override all methods if you don't need to.

eg

public abstract class CondimentDecorator extends Beverage {  
    Beverage beverageToDecorate;

    public CondimentDecorator(Beverage beverageToDecorate) {
        this.beverageToDecorate = beverageToDecorate;
    }

    public String getDescription() {
        return beverageToDecorate.getDescription();
    }

    public double cost() {
        return beverageToDecorate.cost();
    }
} 

这篇关于头先设计模式-使用Starbuzz的装饰器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆