public abstract class Beverage
{
protected string description = "Unknown Description";
public virtual string getDescription()
{
return description;
}
public abstract double Cost();
}
public class Espresso : Beverage
{
public Espresso()
{
description = "Espresso";
}
public override double Cost()
{
return 1.99;
}
}
public class HouseBlend : Beverage
{
public HouseBlend()
{
description = "Hous eBlend";
}
public override double Cost()
{
return 0.85;
}
}
public abstract class CondimentDecorator : Beverage
{
//public abstract new string getDescription();
}
public class Mocha : CondimentDecorator
{
Beverage beve;
public Mocha(Beverage b)
{
beve = b;
}
public override string getDescription()
{
return beve.getDescription() + ", Mocha";
}
public override double Cost()
{
return 0.1 + beve.Cost();
}
}
public class Wisp : CondimentDecorator
{
Beverage beve;
public Wisp(Beverage b)
{
beve = b;
}
public override string getDescription()
{
return beve.getDescription() + ", Wishp";
}
public override double Cost()
{
return 0.9 + beve.Cost();
}
}
public class test : CondimentDecorator
{
//Beverage beve;
public test()
{
//beve = b;
}
public override string getDescription()
{
//return beve.getDescription() + ", Wishp";
return "test";
}
public override double Cost()
{
//return 0.9 + beve.Cost();
return 1.1;
}
}
{
protected string description = "Unknown Description";
public virtual string getDescription()
{
return description;
}
public abstract double Cost();
}
public class Espresso : Beverage
{
public Espresso()
{
description = "Espresso";
}
public override double Cost()
{
return 1.99;
}
}
public class HouseBlend : Beverage
{
public HouseBlend()
{
description = "Hous eBlend";
}
public override double Cost()
{
return 0.85;
}
}
public abstract class CondimentDecorator : Beverage
{
//public abstract new string getDescription();
}
public class Mocha : CondimentDecorator
{
Beverage beve;
public Mocha(Beverage b)
{
beve = b;
}
public override string getDescription()
{
return beve.getDescription() + ", Mocha";
}
public override double Cost()
{
return 0.1 + beve.Cost();
}
}
public class Wisp : CondimentDecorator
{
Beverage beve;
public Wisp(Beverage b)
{
beve = b;
}
public override string getDescription()
{
return beve.getDescription() + ", Wishp";
}
public override double Cost()
{
return 0.9 + beve.Cost();
}
}
public class test : CondimentDecorator
{
//Beverage beve;
public test()
{
//beve = b;
}
public override string getDescription()
{
//return beve.getDescription() + ", Wishp";
return "test";
}
public override double Cost()
{
//return 0.9 + beve.Cost();
return 1.1;
}
}
以上代码来自 HEAD FIRST ,红色的virtual是原文中没有的, 调料类中的注释也是没有的,相当于,在原文中,基类里面的getDescription函数不是虚函数,在调料类里面抽象化了,
按照JAVA的理解,实际上也没错,毕竟饮料类GetDescription是不需要覆写的,只要把description设置一下就OK了, 调料里面要覆写
但是在C#中运行是有问题的,我猜,C#在发现基类中的GetDescription不是虚方法后,调料类实例化后,调用的Get函数,都是基类的,
所以,为了适应.NET平台,要把基类的get虚拟化,因为virtual不要求子类一定要覆写这个方法,只是说,可以覆写,所以不影响饮料类.
这里还是感慨一下,细节决定成败啊!