原文连接
译者:smallclover
我的翻译,由于英语水平的缘由可能会词不达意,十分欢迎各位读者指出其中的错误,但愿能对读者有1%的用处,谢谢!java
装饰器模式容许使用者将新功能添加到现有的对象而不须要改变它的数据结构。这种类型的设计模式来源于结构型模式,该设计模式将会去包装一个现有的类。
这种设计模式会常见一个装饰器类,它包装了原始类,而且在不改变原始类的方法的基础之上添加额外的新的功能。
咱们将经过下面的例子来展现如何使用装饰器模式,在接下来的例子中咱们将用颜色来装饰图形,但不须要修改图形的类。设计模式
咱们将建立一个Shape接口和实现该接口的具体类。而后在建立一个抽象的ShaperDecorator
类,该类也实现了Shape
接口,而且持有一个Shape
类的对象。RedShapeDecorator
做为具体类实现了ShapeDecorator
。DecoratorPatternDemo
,做为咱们的demo类将会去使用RedShapeDecorator
去装饰Shape
对象。数据结构
建立接口
Shape.javaide
public interface Shape { void draw(); }
建立具体的类来实现Shape
接口
Rectangle.javathis
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } }
Circle.javaspa
public class Circle implements Shape { @Override public void draw() { System.out.println("Shape: Circle"); } }
建立抽象的装饰器类实现Shape
接口。
ShapeDecorator.java翻译
public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; } public void draw(){ decoratedShape.draw(); } }
建立具体的装饰器类,该类继承了ShaperDecorator
类。
RedShapeDecorator.java设计
public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape){ System.out.println("Border Color: Red"); } }
使用RedShapeDecorator
装饰Shape
对象。
DecoratorPatternDemo.javacode
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 with normal border"); circle.draw(); System.out.println("\nCircle of red border"); redCircle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); } }
检验输出orm
Circle with normal border Shape: Circle Circle of red border Shape: Circle Border Color: Red Rectangle of red border Shape: Rectangle Border Color: Red