设计模式——结构型

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:

相关推荐
博风11 小时前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶12 小时前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
geovindu17 小时前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
拆房老料18 小时前
【第四部分:Agentic 智能体设计模式】15.为什么 Agent 也需要设计模式
人工智能·设计模式·ai·ai-native
geovindu19 小时前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Lost of 程序猿19 小时前
责任链模式实战:审批流里“层层把关“的艺术
后端·设计模式·asp.net·责任链模式
希洛兔1 天前
状态模式详解:让对象随内部状态自动改变行为
java·设计模式·状态模式
博风2 天前
7、设计模式应用举例:策略模式:加密、解密文件
设计模式·策略模式
4SAPI2 天前
Provider Adapter设计模式:如何让AI应用支持多个模型
网络·人工智能·设计模式
geovindu2 天前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式