Design Patterns - Decorator Pattern(译)

原文连接
译者:smallclover
我的翻译,由于英语水平的缘由可能会词不达意,十分欢迎各位读者指出其中的错误,但愿能对读者有1%的用处,谢谢!java

设计模式-装饰器模式

装饰器模式容许使用者将新功能添加到现有的对象而不须要改变它的数据结构。这种类型的设计模式来源于结构型模式,该设计模式将会去包装一个现有的类。
这种设计模式会常见一个装饰器类,它包装了原始类,而且在不改变原始类的方法的基础之上添加额外的新的功能。
咱们将经过下面的例子来展现如何使用装饰器模式,在接下来的例子中咱们将用颜色来装饰图形,但不须要修改图形的类。设计模式

实现

咱们将建立一个Shape接口和实现该接口的具体类。而后在建立一个抽象的ShaperDecorator类,该类也实现了Shape接口,而且持有一个Shape类的对象。
RedShapeDecorator 做为具体类实现了ShapeDecoratorDecoratorPatternDemo,做为咱们的demo类将会去使用RedShapeDecorator去装饰Shape对象。数据结构

clipboard.png

第一步

建立接口
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
相关文章
相关标签/搜索