Java设计模式之--装饰模式Decorator Pattern
首先,当我们遇到什么样的问题时,我们要用Decorator解决呢?
例如,生活中身边最常见的水杯,不仅有不同大小,而且有不同颜色等,我们按继承的做法:
图画的难看了,大家将就一下,咱也不是美工出身 O(∩_∩)O~
abstract class Cup{ abstract void volume();}interface Color{void color();}//实体类Codeclass Cup300ml extends Cup { public void volume(){ System.out.print("300ml cup"); }}class Cup500ml extends Cup{public void volume(){System.out.print("500ml cup");}}class Cup700ml extends Cup{public void volume(){System.out.print("700ml cup");}}//各种颜色的添加class Cup300mlRed extends Cup300ml implements Color{@Overridepublic void color() {System.out.print("red color");}}class Cup500mlRed extends Cup300ml implements Color{@Overridepublic void color() {System.out.print("red color");}}class Cup700mlRed extends Cup300ml implements Color{@Overridepublic void color() {System.out.print("red color");}}class Cup300mlYellow extends Cup300ml implements Color{@Overridepublic void color() {System.out.print("yellow color");}}
abstract class Cup{ abstract void volume();}//模式结构图中的Componentinterface Color{void color();}//模式结构图中的ConcreteComponentclass Red implements Color{@Overridepublic void color() {System.out.print("red color");}}class Yellow implements Color{@Overridepublic void color() {System.out.print("yellow color");}}//模式结构图中的Decoratorclass Cup300ml extends Cup { //在类里面,添加组合接口类Color,作为私有成员 private Color mColor; public void volume(){ System.out.print("300ml cup "); mColor.color(); } //在构造器中,将组合成员以参数形式传入 public Cup300ml(Color c){ mColor = c; }}class Cup500ml extends Cup{ private Color mColor; public void volume(){ System.out.print("500ml cup "); mColor.color(); } public Cup500ml(Color c){ mColor = c; }}class Cup700ml extends Cup{ private Color mColor; public void volume(){ System.out.print("700ml cup "); mColor.color(); } public Cup700ml(Color c){ mColor = c; }}
public class Test{ public static void main(String a[]){Red red = new Red();Yellow yellow = new Yellow();Cup300ml cup300 = new Cup300ml(red);Cup500ml cup500 = new Cup500ml(yellow);cup300.volume();cup500.volume(); }}