gpt4 book ai didi

c# - 装饰者模式的实现

转载 作者:可可西里 更新时间:2023-11-01 08:06:17 29 4
gpt4 key购买 nike

尝试从“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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com