public interface Shape {
void draw();
}
public class Circle implements Shape {
private static final String TAG = "zhoumao";
@Override
public void draw() {
Log.d(TAG, "draw: " + getClass().getName());
}
}
public class Rectangle implements Shape {
private static final String TAG = "zhoumao";
@Override
public void draw() {
Log.d(TAG, "draw: "+"Shape: Rectangle");
}
}
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator {
private static final String TAG = "zhoumao";
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
super.draw();
setRedBorder(super.decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
Log.d(TAG, "setRedBorder: " + "Border Color: Red");
}
}
public class RotateShapeDecorator extends ShapeDecorator {
private static final String TAG = "zhoumao";
public RotateShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
super.draw();
setRotate();
}
private void setRotate(){
Log.d(TAG, "setRotate: ");
}
}
测试代码:
Log.d(TAG, "Circle with normal border");
circle.draw();
Shape redCircle = new RedShapeDecorator(new Circle());
Log.d(TAG, "\n******Circle of red border");
redCircle.draw();
Shape redRectangle = new RedShapeDecorator(new Rectangle());
Log.d(TAG, "\n********Rectangle of red border");
redRectangle.draw();
Log.d(TAG, "\n**********Rectangle rotate of red border");
Shape allRect = new RotateShapeDecorator(redRectangle);
allRect.draw();
结果
05-06 05:10:40.650 7937-7937/? D/zhoumao: Circle with normal border
05-06 05:10:40.650 7937-7937/? D/zhoumao: draw: com.sankuai.tantan.decorator.Circle
05-06 05:10:40.650 7937-7937/? D/zhoumao: ******8Circle of red border
05-06 05:10:40.650 7937-7937/? D/zhoumao: draw: com.sankuai.tantan.decorator.Circle
05-06 05:10:40.650 7937-7937/? D/zhoumao: setRedBorder: Border Color: Red
05-06 05:10:40.650 7937-7937/? D/zhoumao: ********Rectangle of red border
05-06 05:10:40.650 7937-7937/? D/zhoumao: draw: Shape: Rectangle
05-06 05:10:40.650 7937-7937/? D/zhoumao: setRedBorder: Border Color: Red
05-06 05:10:40.650 7937-7937/? D/zhoumao: **********Rectangle rotate of red border
05-06 05:10:40.650 7937-7937/? D/zhoumao: draw: Shape: Rectangle
05-06 05:10:40.650 7937-7937/? D/zhoumao: setRedBorder: Border Color: Red
05-06 05:10:40.650 7937-7937/? D/zhoumao: setRotate: