跟着Netty 学习 23 种设计模式

以下是 Netty 框架中涉及的 23 种设计模式的分类、技术原理及代码示例:

一、创建型模式

1. 工厂方法模式 (Factory Method)

作用:定义创建对象的接口,由子类决定实例化哪个类。

Netty 实现

  • ChannelFactory 工厂:根据配置创建不同类型的 Channel(如 NIO、Epoll)。
ChannelFactory factory = new NioServerSocketChannelFactory(
    Executors.newCachedThreadPool(),
    Executors.newCachedThreadPool()
);
ServerBootstrap bootstrap = new ServerBootstrap(factory); // 通过工厂创建 Channel
2. 抽象工厂模式 (Abstract Factory)

作用:创建一组相关或依赖的对象,而无需指定具体类。

Netty 实现

  • EventLoopGroup 抽象工厂:根据配置创建不同事件循环组(如 NIO、Epoll)。
EventLoopGroup group = new NioEventLoopGroup(); // NIO 事件循环组
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group); // 设置抽象工厂
3. 单例模式 (Singleton)

作用:确保一个类只有一个实例,并提供全局访问点。

Netty 实现

  • ResourceLeakDetector 实例:通过静态内部类实现线程安全的单例。
public class ResourceLeakDetector {
    private static class Holder {
        static final ResourceLeakDetector INSTANCE = new ResourceLeakDetector();
    }

    public static ResourceLeakDetector getInstance() {
        return Holder.INSTANCE;
    }
}
4. 建造者模式 (Builder)

作用:逐步构建复杂对象,允许用户通过链式调用设置属性。

Netty 实现

  • ServerBootstrap 建造者:通过链式调用配置服务端参数。
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel ch) {
                 ch.pipeline().addLast(new EchoServerHandler());
             }
         }); // 链式调用配置
5. 原型模式 (Prototype)

作用:通过克隆现有对象创建新实例。

Netty 实现

  • ByteBuf 克隆:通过 ByteBuf.copy() 创建缓冲区副本。
ByteBuf buf = Unpooled.buffer(1024);
buf.writeBytes("Hello, Netty".getBytes());
ByteBuf clonedBuf = buf.copy(); // 创建副本

二、结构型模式

6. 适配器模式 (Adapter)

作用:将接口转换为客户端期望的另一个接口。

Netty 实现

  • ChannelInboundHandlerAdapter 适配器:适配不同处理器接口。
public class SimpleHandlerAdapter extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 适配具体处理逻辑
    }
}
7. 装饰器模式 (Decorator)

作用:动态为对象添加附加功能。

Netty 实现

  • ChannelHandler 装饰器:通过 ChannelDuplexHandler 添加日志功能。
public class LoggingHandler extends ChannelDuplexHandler {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("Received: " + msg);
        super.channelRead(ctx, msg);
    }
}
8. 代理模式 (Proxy)

作用:通过代理对象控制对原对象的访问。

Netty 实现

  • LocalChannel 代理:通过本地代理实现跨线程通信。
EventLoopGroup group = new DefaultEventLoopGroup();
LocalChannel channel = new LocalChannel(group.next());
channel.writeAndFlush("Hello"); // 通过代理发送消息
9. 外观模式 (Facade)

作用:为复杂子系统提供简化的接口。

Netty 实现

  • Bootstrap 外观:封装服务端/客户端启动流程。
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.bind(8080).sync(); // 简化服务端启动
10. 桥接模式 (Bridge)

作用:将抽象与实现解耦,使两者可以独立变化。

Netty 实现

  • Channel 桥接:桥接不同传输实现(如 NIO、Epoll)。
Channel channel = new NioSocketChannel(); // NIO 实现
// Channel channel = new EpollSocketChannel(); // Epoll 实现
11. 组合模式 (Composite)

作用:将对象组合成树形结构,以表示“部分-整体”的层次结构。

Netty 实现

  • ChannelPipeline 组合:通过组合模式管理处理器链。
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new Handler1());
pipeline.addLast(new Handler2()); // 组合处理器
12. 享元模式 (Flyweight)

作用:共享对象以减少内存占用。

Netty 实现

  • ByteBufAllocator 复用:通过对象池复用 ByteBuf 对象。
ByteBufAllocator allocator = ch.alloc();
ByteBuf buf1 = allocator.buffer(1024);
ByteBuf buf2 = allocator.buffer(1024); // 复用缓冲区

三、行为型模式

13. 模板方法模式 (Template Method)

作用:定义算法骨架,将某些步骤延迟到子类实现。

Netty 实现

  • ChannelInboundHandlerAdapter 模板:定义处理器骨架,子类实现具体步骤。
public abstract class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 公共逻辑(如解码)
        onChannelRead(ctx, msg); // 调用子类实现
    }

    protected abstract void onChannelRead(ChannelHandlerContext ctx, Object msg);
}
14. 观察者模式 (Observer)

作用:定义对象间的一对多依赖,当一个对象状态改变时,所有依赖者收到通知。

Netty 实现

  • ChannelFutureListener 监听器:监听 I/O 操作完成事件。
ChannelFuture future = ch.writeAndFlush("Hello");
future.addListener((ChannelFutureListener) f -> {
    if (f.isSuccess()) {
        System.out.println("Write successful");
    } else {
        System.err.println("Write failed");
    }
});
15. 策略模式 (Strategy)

作用:定义一系列算法,并将每个算法封装起来,使它们可以互换。

Netty 实现

  • EventLoop 策略:根据配置选择不同的事件循环策略(如 NIO、Epoll)。
EventLoopGroup group = new NioEventLoopGroup(); // NIO 策略
// EventLoopGroup group = new EpollEventLoopGroup(); // Epoll 策略
16. 命令模式 (Command)

作用:将请求封装为对象,以便用不同的请求、队列或日志参数化其他对象。

Netty 实现

  • ChannelPromise 命令:封装 I/O 操作请求。
ChannelPromise promise = ch.newPromise();
ch.writeAndFlush("Hello", promise); // 封装写操作请求
17. 责任链模式 (Chain of Responsibility)

作用:将请求的发送者和接收者解耦,使多个对象都有机会处理请求。

Netty 实现

  • ChannelPipeline 责任链:通过处理器链处理 I/O 事件。
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new Handler1());
pipeline.addLast(new Handler2()); // 责任链处理
18. 备忘录模式 (Memento)

作用:捕获并保存对象的内部状态,以便后续恢复。

Netty 实现

  • ChannelConfig 状态保存:通过 ChannelConfig 保存通道配置快照。
ChannelConfig config = ch.config();
config.setAutoRead(false); // 修改状态
config.setAutoRead(true); // 恢复状态
19. 状态模式 (State)

作用:允许对象在内部状态改变时改变行为。

Netty 实现

  • ChannelState 状态管理:通过状态机管理通道状态。
public enum ChannelState {
    CONNECTED,
    DISCONNECTED,
    CLOSED
}

// 状态管理
public class Channel {
    private ChannelState state = ChannelState.CONNECTED;

    public void close() {
        state = ChannelState.CLOSED; // 修改状态
    }
}
20. 访问者模式 (Visitor)

作用:在对象结构中定义新操作,而无需修改结构本身。

Netty 实现

  • ChannelHandler 访问者:通过访问者模式遍历处理器链。
public interface ChannelHandlerVisitor {
    void visit(ChannelHandler handler);
}

// 具体访问者
public class LoggingVisitor implements ChannelHandlerVisitor {
    @Override
    public void visit(ChannelHandler handler) {
        System.out.println("Handler: " + handler.getClass().getName());
    }
}
21. 解释器模式 (Interpreter)

作用:给定一种语言,定义其文法表示,并构建解释器来解释语言中的句子。

Netty 实现

  • HttpObjectDecoder 解释器:解析 HTTP 协议。
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) {
        ch.pipeline().addLast(new HttpServerCodec()); // 解析 HTTP 协议
    }
}
22. 迭代器模式 (Iterator)

作用:提供一种顺序访问集合元素的方法,而无需暴露其内部表示。

Netty 实现

  • ChannelHandlerContext 迭代器:遍历处理器链中的处理器。
ChannelHandlerContext ctx = ch.pipeline().firstContext();
while (ctx != null) {
    System.out.println(ctx.handler().getClass().getName());
    ctx = ctx.next();
}
23. 中介者模式 (Mediator)

作用:定义一个中介对象来封装一系列对象之间的交互。

Netty 实现

  • EventLoop 作为中介者:协调 ChannelChannelPipeline 等组件之间的交互。
public class EventLoop {
    public void execute(Runnable task) {
        // 协调任务执行
    }
}

// 中介者协调
public class Channel {
    private final EventLoop eventLoop;

    public void write(Object msg) {
        eventLoop.execute(() -> {
            // 执行写操作
        });
    }
}

总结

Netty 框架通过灵活运用 23 种设计模式,实现了高扩展性、低耦合性和灵活性。这些模式覆盖了对象创建、结构组织、行为交互等各个方面,是学习 Java 框架设计的经典案例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值