请你描述一下超人的体貌特征,你最先想到的是什么,没错一条外穿的红色小裤裤。那我问你要是超人不穿这个东东,他还算不算超人,答案是当然算了,毕竟超人是公众人物要注意影响嘛。
接着我们把这个超人比作一个我们原来已经实现了的类,外穿的红色小裤裤是我们现在要在这个类中扩展的功能,你会怎么实现。你会说很简单,直接在这个类中加个方法不就行了,但你想过没有,超人的职责是守护和平,其他的只是他的陪衬而已,超人外穿什么并不重要,显然这样做不符合单一职责原则。那你又会说了,继承下不就好了,是,继承下确实没有问题了,但这要看超人能不能答应,超人想穿别的怎么办。他想穿披风,给他建了个子类,他想戴帽子又给他建了个子类,怎么着,超人外出还要整个大背包,把这些都背上不成,显然这样并不合理。超人的逼格必须得拉满呀,整个大背包像什么话,那必须超人想要穿什么,就能变出什么来(插拔式)。
好了,大话讲完了,咱们要回归正题了,讲点实际的东西了。
既然说继承不能满足需求,那只剩下了组合这一条路了,而恰恰装饰器模式就是建立在组合之上的,所以它的核心是组合。
那这不就好实现了嘛,代码如下,仅供参考:
public class Test { public static void main(String[] args) { ComponentRole componentRole = new ChaoRen(); ComponentRole decoratorRole = new ConcreteDecoratorRole(componentRole); decoratorRole.hp(); decoratorRole.wc(); } } class ChaoRen implements ComponentRole{ private String chaoNengli = "超能力"; public void hp(){ System.out.println("超人通过"+chaoNengli+"守护和平"); } public void wc(){ System.out.print("超人外穿了"); } } // 抽象构建角色 interface ComponentRole{ void hp(); void wc(); } class DecoratorRole implements ComponentRole{ // 组合 private ComponentRole componentRole; public DecoratorRole(ComponentRole componentRole){ this.componentRole = componentRole; } @Override public void hp() { componentRole.hp(); } @Override public void wc() { componentRole.wc(); } } // 具体装饰角色 class ConcreteDecoratorRole extends DecoratorRole{ public ConcreteDecoratorRole(ComponentRole componentRole) { super(componentRole); } // 现在外穿 public void wc(){ super.wc(); yf(); } public void hp(){ super.hp(); } public void yf(){ System.out.println("披风、帽子和红色小裤裤"); } public void yf1(){ System.out.println("其他"); } }
运行结果如下:
超人通过超能力守护和平
超人外穿了披风、帽子和红色小裤裤
so easy好吧,那还不赶快自己试一试吧。