设计模式3:代理、适配器、装饰器模式

代理模式(Proxy Pattern)

代理模式的本质是⼀个中间件,主要⽬的是解耦合服务提供者和使⽤者。使⽤者通过代理间接访问服务提供者,便于后者的封装和控制。是⼀种结构型设计模式。

静态代理和动态代理区别

  • 静态代理:编译时生成代理类,需要手动编写代理逻辑,代理类和目标类实现同一接口。
  • 动态代理:运行时生成代理类 ,通过反射机制动态创建代理对象,无需手动编写代理类。如JDK的Proxy类,或CGLIB动态代理

代理模式应用场景

如Spring AOP编程,通过动态代理实现切面编程(如事务管理、日志记录)。若目标类实现接口则用JDK代理,否则用CGLIB

适配器模式

应用程序中有两个不同接口的类进行通信,应用某个中间件来完成通信过程,中间件就是适配器。所谓适配器模式就是将⼀个类的接⼝,转换成客户期望的另⼀个接⼝。比如:插头转换器

分为两类:

  • 类适配器,通过类继承实现适配
  • 对象适配器,通过类对象组合来实现适配

以下是对象适配器的示例代码,将220V电压转为5V电压

java 复制代码
// 目标接口,5V充电口
interface Target {
    int get5V();
}

// 被适配的类,220V电源
class Adaptee220V {
    public int get220V() {
        return 220;
    }
}

//对象适配器,通过组合实现
public class ObjectAdapter implements Target {
    private Adaptee220V adaptee;
    public ObjectAdapter(Adaptee220V adaptee) {
        this.adaptee = adaptee;
    }
    @Override
    public int get5V() {
        return adaptee.get220V() / 44;
    }
}
//客户端代码使用
public class AdapterDemo {
    public static void main(String[] args) {
        Target objectAdapter = new ObjectAdapter(new Adaptee220V());
        System.out.println("对象适配器输出:" + objectAdapter.get5V());
    }
}

装饰器模式

装饰器模式主要对现有的类对象进⾏包裹和封装,以期望在不改变类对象及其类定义的情况下,为对象添加额外功能。是⼀种结构型模式。

核心角色有4类:

  • Component抽象组件:定义对象接口
  • ConcreteComponent:具体组件,被装饰对象的类定义;
  • Decorator:装饰对象的抽象类,继承/实现Component
  • ConcreteDecorator具体装饰器:添加具体额外功能

下面是开发一个权限校验装饰器的示例代码,根据不同接口动态添加权限校验

java 复制代码
//核心接口
interface ApiHandler {
    String handle(String request);
}

//具体API实现
class UserApiHandler implements ApiHandler {
    @Override
    public String handle(String request) {
        return "User data";
    }
}

//权限装饰器基类
abstract class AuthDecorator implements ApiHandler {
    protected ApiHandler wrapped;
    public AuthDecorator(ApiHandler wrapped) {
        this.wrapped = wrapped;
    }
    public abstract String handle(String request);
}

//具体权限装饰器,管理员校验
public class AdminAuthDecorator extends AuthDecorator {
    public AdminAuthDecorator(ApiHandler wrapped) {
        super(wrapped);
    }
    
    @Override
    public String handle(String request) {
        if ("管理员".equals(request)) {
            return "权限错误";
        }
        return wrapped.handle(request);
    }
}

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