我喜欢户外,然后常常去逛户外装备的店子,一般买了自行车等大件,再买登山包,登山鞋等配件就会有优惠。比如买了辆Giant的车,然后买个bag就有优惠,本案例将配件作为装饰者,简单的实现装饰者模式,对于继承,多态掌握的还是很迷惑。有错误还请各位看官帮忙指出,仪器共同进步!
首先定义一个超类Buybike
public abstract class Buybike { protected string description="To Get a Bike"; public virtual string getDescription() { return description; } public abstract string Cost(); }
超类下面定义一个装饰者超类OtherDecorator(所有装饰者【案例中配件】的父类)
public abstract class OtherDecorator:Buybike { //只是为了将装饰者全部置于其下,无具体实现方法 }
下面是两个被装饰的类Giant Merida(捷安特,美利达)
class Merida:Buybike { public Merida() { description = "Merida"; } public override string Cost() { return "2000RMB"; } } public class Giant : Buybike { public Giant() { description = "Giant"; } public override string Cost() { return "3000RMB"; } }
接下去是所有装饰者(配件),全部继承自OtherDecorator
class AddShirt:OtherDecorator { private Buybike buyBike; public AddShirt(Buybike buyBike) { this.buyBike = buyBike; } public override string getDescription() { return buyBike.getDescription() + "Add a shirt"; } public override string Cost() { return buyBike.Cost() + "shirt's money:600RMB"; } } class AddShoes:OtherDecorator { private Buybike buyBike; public AddShoes(Buybike buyBike) { this.buyBike = buyBike; } public override string getDescription() { return buyBike.getDescription() + "Add a shoes"; } public override string Cost() { return buyBike.Cost() + "shoe's money:300RMB"; } } class AddBag:OtherDecorator { private Buybike buyBike; public AddBag(Buybike buyBike) { this.buyBike = buyBike; } public override string getDescription() { return buyBike.getDescription() + "Add a bag"; } public override string Cost() { return buyBike.Cost() + "bag's money:200RMB"; } }
程序运行如下:
class Program { static void Main(string[] args) { Buybike a= new Giant(); a = new AddBag(a); a = new AddShirt(a); Console.WriteLine(a.Cost()); Console.WriteLine(a.getDescription()); } }
此模式好处:装饰者和被装饰者从相同基类派生,类型之间的转化非常方便,适合多态的实现。
具体到例子,此处的a具体到是一个基类变量,把它指到下面的子类不必进行类型转化,而且a具体是什么类型,得在运行时才能确定,程序耦合度大大降低。