设计模式——结构型

1.装饰器模式

要素:装饰器,装饰对象
为待装饰对象中某一结构特征添加内容,而不是新建一个特征

/**
 * 装饰对象
 */
public interface Shape {
   
    public void draw();
}
/**
 * 具体装饰对象
 */
public class Circle implements Shape{
   
    private String TAG = "Circle";
    @Override
    public void draw() {
   
        Log.d(TAG,"draw circle");
    }
}

/**
 * 装饰器
 */
public abstract class ShapeDecorator implements Shape{
   
    protected Shape shape;
    private String TAG = "ShapeDecorator";

    public ShapeDecorator(Shape shape) {
   
        this.shape = shape;
    }
}
/**
 * 具体装饰器,当只有一个待装饰对象时可不需要抽象装饰器
 */
public class ColorDecorator extends ShapeDecorator {
   
    private String TAG = "ColorDecorator";
    public ColorDecorator(Shape shape) {
   
        super(shape);
    }

    //原结构方法
    public void draw() {
   
        shape.draw();
        setColor();
    }

    //给原结构添加的装饰
    private void setColor() {
   
        Log.d(TAG,"set color");
    }
}

//测试
Circle circle = new Circle();
ColorDecorator colorCircle = new ColorDecorator(circle);
colorDecorator.draw();

输出log:
在这里插入图片描述

相关推荐

  1. 设计模式-结构模式

    2023-12-15 03:22:04       40 阅读
  2. Golang 设计模式结构

    2023-12-15 03:22:04       12 阅读
  3. Python 设计模式结构

    2023-12-15 03:22:04       6 阅读
  4. 设计模式_结构模式_适配器模式

    2023-12-15 03:22:04       31 阅读
  5. 设计模式结构模式)外观模式

    2023-12-15 03:22:04       26 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-15 03:22:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-15 03:22:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-15 03:22:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-15 03:22:04       18 阅读

热门阅读

  1. Nacos 系统参数介绍

    2023-12-15 03:22:04       42 阅读
  2. [云原生基础] 浅谈 Docker

    2023-12-15 03:22:04       40 阅读
  3. Python 如何进行游戏开发?

    2023-12-15 03:22:04       36 阅读
  4. shell学习---杂谈

    2023-12-15 03:22:04       33 阅读
  5. Heap Sort Algorithm

    2023-12-15 03:22:04       31 阅读
  6. SSH连接慢的问题

    2023-12-15 03:22:04       40 阅读