首页 > 代码库 > 装饰者模式
装饰者模式
首先:我们建立一个超类: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、我们需要加什么装饰非常容易
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。