装饰者模式
首先:我们建立一个超类:Clothes:
public abstract class Clothes { public string Look = "beautiful"; public string Getlook() { return Look; } public abstract double Cost(); }
考虑到将不同的独立出来:我们写一个类:此类暂时和本方向无关,可以不注意Dress:
public abstract class Dress : Clothes { public abstract string WithWho(); }
衣服有不同的,我们独立出2种来:Lap与Pants:
public class Lap : Clothes { public Lap () { Look = "more beautiful with lap"; } public override double Cost() { return 100; } } public class Pants : Clothes { public Pants () { Look = "more beautiful with pants"; } public override double Cost() { return 88; } }
这个时候我们写一个装饰品类出来装饰Lap与Pants,此类Bag(注意此类必须继承Clothes):
public class Bag : Dress { public Clothes Clothes; public Bag(Clothes clothes) { Clothes = clothes; Look = Clothes.Getlook() +WithWho()+ " bag"; } public override sealed string WithWho() { return "need"; } public override double Cost() { return 10 + Clothes.Cost(); } }
这个时候我们就可以装饰他了:
static void Main(string[] args) { Clothes clothes=new Lap(); Console.WriteLine(clothes.Getlook()+" need "+clothes.Cost()); Clothes clothes2=new Pants(); clothes2=new Bag(clothes2); clothes2=new Bag(clothes2); Console.WriteLine(clothes2.Getlook() + " need " + clothes2.Cost()); Console.ReadLine(); }
结果为:more beautiful with lap need 100
more beautiful with pantsneed bagneed bag need 108
此模式好处:1、此模式能解决独立的类过多的问题
2、我们需要加什么装饰非常容易