设计模式——结构型

1.装饰器模式

要素:装饰器,装饰对象

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

java 复制代码
/**
 * 装饰对象
 */
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:

相关推荐
xiaofeiyang1507 小时前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)21 小时前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki2 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅662 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa2 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki2 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent
sarasuki2 天前
如何让 Agent 安全运行你的命令 :命令分级 + Hook + 读写锁
人工智能·设计模式·agent
Zane19942 天前
技术不难,为什么项目却越改越不敢动?聊聊复杂系统开发该怎么想
设计模式
geovindu2 天前
rust: Factory Method Pattern
开发语言·设计模式·rust·工厂方法模式·创建型模式
一木 之林3 天前
第 8 节 C++ 设计模式在 AI 推理 SDK 和 Agent 工具运行时中如何落地
c++·人工智能·设计模式