问题描述
- JAVA和C#执行HeadFirst装饰者模式的结果差异,求解?
-
JAVA版
//Beverage.java
public abstract class Beverage {
String description = "Unkown Beverage";public String GetDescription(){
return description;
}public abstract double Cost();
}
//CondimentDecorator.java
public abstract class CondimentDecorator extends Beverage {public abstract String GetDescription();
}
//Espresso.java
public class Espresso extends Beverage {
public Espresso()
{
description = "Espresso";
}public double Cost() {
return 1.99;
}}
//HouseBlend .java
public class HouseBlend extends Beverage {public double Cost() {
return .89;
}
public HouseBlend()
{
description = "House Blend Coffee";
}
}//Mocha.java
public class Mocha extends CondimentDecorator {Beverage beverage;
public Mocha(Beverage beverage)
{
this.beverage = beverage;
}public String GetDescription() {
return beverage.GetDescription() + ", Mocha";
}public double Cost() {
return .20 + beverage.Cost();
}}
//main.java
public class Main {
/**
- @param args
*/
public static void main(String[] args) {
Beverage bv = new Espresso();
System.out.println(bv.GetDescription() +" $"+bv.Cost());
Beverage bv2 = new HouseBlend();
bv2 = new Mocha(bv2);
System.out.println(bv2.GetDescription() +" $"+bv2.Cost());
}}
运行结果
Espresso $1.99
House Blend Coffee, Mocha $1.09##############################
C#版
//Beverage.cs
public abstract class Beverage
{
public string description = "Unkown Beverage";public string GetDescription()
{
return description;
}public abstract double Cost();
}//CondimentDecorator.cs
public abstract class CondimentDecorator:Beverage
{
public abstract new string GetDescription();
}//Espresso.cs
public class Espresso : Beverage
{
public Espresso()
{
description = "Espresso";
}
public override double Cost()
{
return 1.99;
}
}//HouseBlend.cs
public class HouseBlend : Beverage
{
public HouseBlend()
{
description = "House Blend Coffee";
}
public override double Cost()
{
return .89;}
}//Mocha.cs
public class Mocha : CondimentDecorator
{
Beverage beverage;
public Mocha(Beverage beverage)
{
this.beverage = beverage;
}public override double Cost()
{
return .20 + beverage.Cost();
}public override string GetDescription()
{
return beverage.GetDescription() + ", Mocha";
}
}Program.cs
class Program
{
static void Main(string[] args)
{
Beverage bv = new Espresso();
Console.WriteLine(bv.GetDescription() + " $"+bv.Cost());Beverage bv2 = new HouseBlend();
bv2 = new Mocha(bv2);
Console.WriteLine(bv2.GetDescription() + " $" + bv2.Cost());
Console.ReadKey();
}
}
运行结果:
Espresso $1.99
Unkown Beverage $1.09 - @param args
解决方案
public abstract new string GetDescription();
->
public abstract string GetDescription();
解决方案二:
java软件体系结构设计模式----装饰者
java装饰者模式
Java装饰者模式