设计模式学习笔记--装饰器模式

本文介绍了装饰器模式的概念及其优势,并通过具体的Java代码示例详细解释了如何实现装饰器模式,展示了如何为现有对象动态地添加新功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

十、装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时不改变其结构。
通过创建一个装饰类,包装原有的类,保持原有类的方法签名不变,提供额外功能。

介绍

动态的给一个对象添加一些额外的新功能,相比生成子类更为灵活。
相比使用继承,装饰模式避免了由继承而引入的静态特征和子类臃肿的现象。
- 优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代方式,可以动态扩展一个现有类的功能。
- 缺点:多层装饰比较复杂。

实现

创建一个Shape接口和实现该接口的实体类,然后欻功能键一个实现Shape接口的装饰类ShapeDecorator
并把Shape对象作为它的实例变量。RedShapeDecorator实现ShapeDecorator的实体类,完成功能扩展。
decorator
- 创建接口

Shape.java

public interface Shape {
  void draw();
}
  • 创建接口实现类

Rectangle.java

public class Rectangle implements Shape {
  @override
  public void draw(){
    System.out.println("Shape : Rectangle");
  }
}

Circle.java

public class Circle implements Shape {
  @override
  public void draw(){
    System.out.println("Shape : Circle");
  }
}
  • 创建抽象的装饰类

ShapeDecorator.java

public abstract class ShapeDecorator implements Shape{
  protected Shape decorateShape;

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

  public void draw(){
    decorateShape.draw();
  }
}
  • 创建实体的装饰类

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");
  }
}
  • 演示

DecoratorPatternDemo.java

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("\n Circle of red border");
    redCircle.draw();

    System.out.println("\n Rectangle 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值