设计模式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);
相关推荐
牛奶咖啡131 小时前
学习设计模式《二十三》——桥接模式
学习·设计模式·桥接模式·认识桥接模式·桥接模式的优点·何时选用桥接模式·桥接模式的使用示例
左灯右行的爱情1 小时前
深度学习设计模式:责任链(Chain of Responsibility)模式(例子+业务场景+八股)
深度学习·设计模式·责任链模式
是2的10次方啊2 小时前
🚀 Spring设计模式大揭秘:23种模式藏在你每天在用的框架里
设计模式
东北南西2 小时前
设计模式-单例模式
前端·javascript·单例模式·设计模式
快乐非自愿3 小时前
掌握设计模式--命令模式
设计模式·命令模式
我希望的一路生花12 小时前
Nik Collection 6.2全新版Nik降噪锐化调色PS/LR插件
人工智能·计算机视觉·设计模式·stable diffusion·aigc
东北南西18 小时前
设计模式-工厂模式
前端·设计模式
JohnYan19 小时前
工作笔记 - 改进的单例应用
javascript·设计模式·bun
郝学胜-神的一滴21 小时前
使用C++11改进工厂方法模式:支持运行时配置的增强实现
开发语言·c++·程序人生·设计模式
Leo来编程21 小时前
设计模式3-模板方法模式
设计模式·模板方法模式