1.装饰器模式
要素:装饰器,装饰对象
为待装饰对象中某一结构特征添加内容,而不是新建一个特征
/*** 装饰对象*/
public interface Shape {public void draw();
}
/*** 具体装饰对象*/
public class Circle implements Shape{private String TAG = "Circle";@Overridepublic void draw() {Log.d(TAG,"draw circle");}
}/*** 装饰器*/
public abstract class ShapeDecorator implements Shape{protected Shape shape;private String TAG = "ShapeDecorator";public ShapeDecorator(Shape shape) {this.shape = shape;}
}
/*** 具体装饰器,当只有一个待装饰对象时可不需要抽象装饰器*/
public class ColorDecorator extends ShapeDecorator {private String TAG = "ColorDecorator";public ColorDecorator(Shape shape) {super(shape);}//原结构方法@Overridepublic void draw() {shape.draw();setColor();}//给原结构添加的装饰private void setColor() {Log.d(TAG,"set color");}
}//测试
Circle circle = new Circle();
ColorDecorator colorCircle = new ColorDecorator(circle);
colorDecorator.draw();
输出log: