c# - 装饰者模式的实现

标签 c# oop design-patterns inheritance decorator

尝试从“Head First Design Patterns”一书中的代码(用 Java 编写)在 C# 中实现装饰器模式。

我刚开始使用 C#,因此对语法还是陌生的,所以我不确定为什么我不能让下面的注释代码行工作。

这是装饰器模式中的第一个抽象基类及其派生类:

using System;

public abstract class Beverage
{
    private String m_description;

    // get a description of the beverage
    public virtual String Description { get { return m_description; } }

    // calculate cost of the beverage
    public abstract double Cost();
}

// HouseBlend coffee implements Beverage
public class HouseBlend : Beverage
{
    // Constructor
    public HouseBlend() { m_description = "House Blend"; }

    // calculate base cost of House Blend
    public override double Cost() { return 0.89; }
}

// DarkRoast coffee implements Beverage
public class DarkRoast : Beverage
{
    // Constructor
    public DarkRoast() { m_description = "Dark Roast"; }

    // calculate base cost of Dark Roast
    public override double Cost() { return 1.00; }
}

// Espresso coffee implements Beverage
public class Espresso : Beverage
{
    // Constructor
    public Espresso() { m_description = "Espresso"; }

    // calculate base cost of Espresso
    public override double Cost() { return 1.99; }
}

违规代码在 Mocha 类的 Cost() 方法中:

using System;

// abstract base class CondimentDecorator is-a Beverage
public abstract class CondimentDecorator : Beverage {}

// Mocha implements the CondimentDecorater
public class Mocha : CondimentDecorator
{
    // Condiment decorator has-a Beverage (recursion!)
    private Beverage m_beverage;

    // Constructor binds the object passed to member var
    public Mocha(Beverage beverage)
    {
        this.m_beverage = beverage;
    }

    // getter implements abstract class Description
    public override String Description
    {
        get
        {
            return m_beverage.Description + ", Mocha";
        }
    }

    // get the Cost of the condiment plus the base-cost
    // of the original beverage
    public new double Cost()               // ERROR: 'Mocha.Cost()' hides inherited
    {                                      // member 'Beverage.Cost()'
        return 0.20 + m_beverage.Cost();
    }
}

最佳答案

new 更改为 override。此外,m_description 应该是 protected

关于c# - 装饰者模式的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959346/

相关文章:

c# - 在 HTML 页面 <%# %> 标签内使用 If Else

c# - 通过 MediatR PipelineBehavior 进行单元测试验证

java - 当字符串中有重复项时,查找子字符串的中间索引

java - REST API 调用是否应该在存储库层上使用 @Repository 进行?

c# - 如果未提供模型,则 ASP.NET MVC 自动模型实例化

c# - 从 Web 服务读取 XML 节点

c# - 在类上调用方法或作为参数传递给另一个类? C#

C++ 子类中某些方法的高效继承

class - 根据上下文仅返回对象中所需数据的最佳模式是什么?

c# - cin/cout 使用什么技术/模式允许例如输出 << x << y?