装饰器模式

装饰器模式

单一职责原则:就一个类而言,应该仅有一个引起它变化的原因。

核心

把一个类中的核心职责和装饰功能分开,被装饰对象当做参数传入装饰者对象。动态地给一个对象添加一些额外的职责。

好处

装饰类和被装饰类可以独立发展,不会相互耦合,把类中的装饰功能从类中搬除,简化原有的类,去除相关类中的重复装饰的逻辑。

例子

情景:本类是形状,用颜色装饰类装饰。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。
//创建一个接口
public interface Shape{
  void draw();
}

//创造实体类Circle实现接口
public class Circle implements Shape {
  public void draw(){
        System.out.println("Shape: Circle");
    }
}

//创建实现接口的实体类Rectangle
public class Rectangle implements Shape {
  public void draw(){
        System.out.println("Shape: Rectangle");
    }
}

//创建实现了 Shape 接口的抽象装饰类。
public abstract class ShapeDecorator implements Shape {
  protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape){
        this.decoratedShape = decoratedShape;
    }

    public void draw(){
        decoratedShape.draw();
    }
}

//创建扩展了 ShapeDecorator 类的实体装饰类。
public class RedShapeDecorator extends ShapeDecorator{

  public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }

    public void draw(){
        decoratedShape.draw();
        setRedBorder(decoratedShape);
    }

    private void setRedBorder(Shape decoratedShape) {
        System.out.println("Border Color: Red");
    }

}


//最后是客户端程序
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();
   }
}

//程序输出
Circle with normal border
Shape: Circle

Circle of red border
Shape: Circle
Border Color: Red

Rectangle of red border
Shape: Rectangle
Border Color: Red

例子来源http://www.runoob.com/design-pattern/decorator-pattern.html

源码在我的代码托管上
装饰者模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值