装饰者模式按照我的理解就是如同每个人都可以穿不同衣服。一个人也可以穿很多不同的衣服,这就是不同衣服对于人的装饰。
简单模拟一下具体适用的场景,用人们的穿戴衣服来模拟。
人可以穿很多不同品牌的衣服。同时穿一双鞋子。要求可以求出不同人群穿戴衣服的价格。
理论上有无数种搭配。我们把穿戴的衣服和鞋子抽象化。用接口表示出来。代码如下:
/*** * 人的衣服属性 * 价钱和简介 */ public interface Clothes { BigDecimal money(); String desc(); }
public class ClothesLiNing implements Clothes{ public Clothes clothes; ClothesLiNing(){ } ClothesLiNing(Clothes clothes){ this.clothes = clothes; } @Override public BigDecimal money() { return new BigDecimal(300).add(clothes.money()); } @Override public String desc() { return "李宁外套" + clothes.desc(); } }
public class ClothesAnTa implements Clothes{ public Clothes clothes; public ClothesAnTa(){} public ClothesAnTa(Clothes clothes){ this.clothes = clothes; } @Override public BigDecimal money() { return new BigDecimal(250).add(clothes.money()); } @Override public String desc() { return "安踏短袖" + clothes.desc(); } }
public class ShoseLiNing implements Clothes{ @Override public BigDecimal money() { return new BigDecimal(1000); } @Override public String desc() { return "李宁韦德之道9"; } }
public class Person { Clothes clothes; Person(){}; Person(Clothes clothes){ this.clothes = clothes; } public BigDecimal getClothesMoney(){ return this.clothes.money(); } public String getDesc(){ return this.clothes.desc(); } }
这样可以解决无数个人穿某个品牌衣服的需求问题