代码详解设计模式--装饰器模式

本文深入探讨了装饰器模式,一种允许在不改变对象结构的情况下为其添加新功能的设计模式。通过具体的Java代码示例,展示了如何使用装饰器模式为形状对象添加颜色属性,使代码更加灵活和可扩展。

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

装饰器模式

  允许向一个现有的对象添加新的功能,同时又不改变其结构。

UML

// 形状接口
public interface Shape {
   void draw();
}

// 圆形
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("画圆");
   }
}

// 方形
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("画方");
   }
}

// 形状装饰器
public abstract class ShapeDecorator implements Shape {
   protected Shape decoratedShape;
 
   public ShapeDecorator(Shape decoratedShape){
      this.decoratedShape = decoratedShape;
   }
 
   public void draw(){
      decoratedShape.draw();
   }  
}

// 红色装饰器
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("外观颜色: 红色");
   }
}

// 使用示例
public class Demo {
   public static void main(String[] args) {
      Shape circle = new Circle();
      Shape square = new Square();
      Shape redCircle = new RedShapeDecorator(new Circle());
      Shape redSquare = new RedShapeDecorator(new Square());
       
      circle.draw();
      square.draw();
      redCircle.draw();
      redSquare.draw();
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值