10) Decorator Pattern
类别:
Structural Pattern
问题:
在不改变接口的前提下增加额外的服务
方案:
示例:
public class DecoratorPatternDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("普通圆"); circle.draw(); System.out.println("\n红框圆"); redCircle.draw(); System.out.println("\n红框矩形"); redRectangle.draw(); } } interface Shape { void draw(); } class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } } class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); } } abstract class ShapeDecorator implements Shape { protected Shape shap; public ShapeDecorator(Shape shap) { this.shap = shap; } public abstract void draw(); } class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape shap) { super(shap); } @Override public void draw() { shap.draw(); setRedBorder(shap); } private void setRedBorder(Shape decoratedShape) { System.out.println("Border Color: Red"); } }
普通圆
Shape: Circle
红框圆
Shape: Circle
Border Color: Red
红框矩形
Shape: Rectangle
Border Color: Red
应用:
不足:(
优化:)