以下是 Dubbo 框架中涉及的 23 种设计模式的分类、技术原理及代码示例:
一、创建型模式
1. 工厂方法模式 (Factory Method)
作用:定义创建对象的接口,由子类决定实例化哪个类。
Dubbo 实现:
Protocol
工厂:通过ExtensionLoader
加载不同协议(如dubbo
、http
)的实现。
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("dubbo");
// 获取 dubbo 协议实现
2. 抽象工厂模式 (Abstract Factory)
作用:创建一组相关或依赖的对象,而无需指定具体类。
Dubbo 实现:
ServiceConfig
工厂:根据配置创建服务提供者或消费者的代理对象。
ServiceConfig<GreetingService> service = new ServiceConfig<>();
service.setInterface(GreetingService.class);
service.setRef(new GreetingServiceImpl());
service.export(); // 导出服务,内部创建代理对象
3. 单例模式 (Singleton)
作用:确保一个类只有一个实例,并提供全局访问点。
Dubbo 实现:
ExtensionLoader
实例:通过静态内部类实现线程安全的单例。
public class ExtensionLoader<T> {
private static final Map<Class<?>, ExtensionLoader<?>> LOADERS = new ConcurrentHashMap<>();
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) LOADERS.get(type);
if (loader == null) {
LOADERS.putIfAbsent(type, new ExtensionLoader<>(type));
loader = (ExtensionLoader<T>) LOADERS.get(type);
}
return loader;
}
}
4. 建造者模式 (Builder)
作用:逐步构建复杂对象,允许用户通过链式调用设置属性。
Dubbo 实现:
ReferenceConfig
建造者:通过链式调用配置服务消费者。
ReferenceConfig<GreetingService> reference = new ReferenceConfig<>();
reference.setInterface(GreetingService.class);
reference.setUrl("dubbo://localhost:12345/GreetingService");
GreetingService service = reference.get(); // 构建服务消费者
5. 原型模式 (Prototype)
作用:通过克隆现有对象创建新实例。
Dubbo 实现:
RpcInvocation
克隆:通过克隆RpcInvocation
创建新的调用对象。
public class RpcInvocation implements Invocation, Serializable, Cloneable {
@Override
public RpcInvocation clone() {
try {
return (RpcInvocation) super.clone(); // 浅克隆
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
二、结构型模式
6. 适配器模式 (Adapter)
作用:将接口转换为客户端期望的另一个接口。
Dubbo 实现:
ProtocolFilterWrapper
适配器:适配不同过滤器链。
public class ProtocolFilterWrapper implements Protocol {
private final Protocol protocol;
public ProtocolFilterWrapper(Protocol protocol) {
this.protocol = protocol;
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) {
return protocol.export(buildInvokerChain(invoker)); // 适配过滤器链
}
}
7. 装饰器模式 (Decorator)
作用:动态为对象添加附加功能。
Dubbo 实现:
Filter
装饰器:为服务调用添加附加功能(如日志、监控)。
public class MonitoringFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) {
long start = System.currentTimeMillis();
Result result = invoker.invoke(invocation);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Invocation elapsed: " + elapsed + "ms");
return result;
}
}
8. 代理模式 (Proxy)
作用:通过代理对象控制对原对象的访问。
Dubbo 实现:
JavassistProxyFactory
代理:通过 Javassist 生成服务接口的代理对象。
public class JavassistProxyFactory extends AbstractProxyFactory {
@SuppressWarnings("unchecked")
@Override
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
}
}
9. 外观模式 (Facade)
作用:为复杂子系统提供简化的接口。
Dubbo 实现:
ReferenceConfig
外观:封装服务消费者配置和引用过程。
ReferenceConfig<GreetingService> reference = new ReferenceConfig<>();
reference.setInterface(GreetingService.class);
reference.setUrl("dubbo://localhost:12345/GreetingService");
GreetingService service = reference.get(); // 简化服务引用
10. 桥接模式 (Bridge)
作用:将抽象与实现解耦,使两者可以独立变化。
Dubbo 实现:
Cluster
桥接:桥接不同集群策略(如 Failover、Failfast)。
public interface Cluster {
<T> Invoker<T> join(Directory<T> directory);
}
// 具体实现(FailoverCluster)
public class FailoverCluster implements Cluster {
@Override
public <T> Invoker<T> join(Directory<T> directory) {
return new FailoverClusterInvoker<>(directory); // 返回 Failover 策略
}
}
11. 组合模式 (Composite)
作用:将对象组合成树形结构,以表示“部分-整体”的层次结构。
Dubbo 实现:
Node
组合:通过组合模式构建服务目录树。
public interface Node {
URL getUrl();
Invoker<?> getInvoker();
}
// 具体节点(DirectoryNode)
public class DirectoryNode implements Node {
private final Directory directory;
@Override
public URL getUrl() {
return directory.getUrl();
}
@Override
public Invoker<?> getInvoker() {
return directory.list(null).iterator().next();
}
}
12. 享元模式 (Flyweight)
作用:共享对象以减少内存占用。
Dubbo 实现:
Invoker
复用:通过Exporter
缓存Invoker
对象。
public class Exporter<T> {
private final Invoker<T> invoker;
public Exporter(Invoker<T> invoker) {
this.invoker = invoker;
}
public Invoker<T> getInvoker() {
return invoker;
}
}
三、行为型模式
13. 模板方法模式 (Template Method)
作用:定义算法骨架,将某些步骤延迟到子类实现。
Dubbo 实现:
AbstractClusterInvoker
模板:定义集群调用流程,子类实现具体步骤。
public abstract class AbstractClusterInvoker<T> implements ClusterInvoker<T> {
@Override
public Result invoke(Invocation invocation) {
// 公共逻辑(如负载均衡、路由)
return doInvoke(invocation); // 调用子类实现
}
protected abstract Result doInvoke(Invocation invocation);
}
14. 观察者模式 (Observer)
作用:定义对象间的一对多依赖,当一个对象状态改变时,所有依赖者收到通知。
Dubbo 实现:
NotifyListener
监听器:监听注册中心事件(如服务上线、下线)。
public interface NotifyListener {
void notify(List<URL> urls);
}
// 具体监听器(RegistryDirectory)
public class RegistryDirectory<T> implements NotifyListener {
@Override
public void notify(List<URL> urls) {
// 处理服务变更通知
}
}
15. 策略模式 (Strategy)
作用:定义一系列算法,并将每个算法封装起来,使它们可以互换。
Dubbo 实现:
LoadBalance
策略:根据配置选择不同的负载均衡策略(如随机、轮询)。
public interface LoadBalance {
<T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation);
}
// 具体策略(RandomLoadBalance)
public class RandomLoadBalance implements LoadBalance {
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
return invokers.get(RandomUtils.nextInt(invokers.size())); // 随机选择
}
}
16. 命令模式 (Command)
作用:将请求封装为对象,以便用不同的请求、队列或日志参数化其他对象。
Dubbo 实现:
RpcInvocation
命令:封装远程调用请求。
public class RpcInvocation implements Invocation, Serializable {
private String methodName;
private Class<?>[] parameterTypes;
private Object[] arguments;
public Object[] getArguments() {
return arguments;
}
}
17. 责任链模式 (Chain of Responsibility)
作用:将请求的发送者和接收者解耦,使多个对象都有机会处理请求。
Dubbo 实现:
Filter
链:通过过滤器链处理服务调用。
public class FilterChain {
private final List<Filter> filters;
public Result invoke(Invoker<?> invoker, Invocation invocation) {
Result result = new Result();
for (Filter filter : filters) {
result = filter.invoke(invoker, invocation); // 依次应用过滤器
if (result.hasException()) {
break;
}
}
return result;
}
}
18. 备忘录模式 (Memento)
作用:捕获并保存对象的内部状态,以便后续恢复。
Dubbo 实现:
Invocation
状态保存:通过RpcInvocation
保存调用状态快照。
public class RpcInvocation implements Invocation, Serializable, Cloneable {
private transient Object[] arguments;
public Object[] getArguments() {
return arguments;
}
public void setArguments(Object[] arguments) {
this.arguments = arguments;
}
}
19. 状态模式 (State)
作用:允许对象在内部状态改变时改变行为。
Dubbo 实现:
ChannelState
状态管理:通过状态机管理网络通道的状态。
public enum ChannelState {
CONNECTED,
DISCONNECTED,
CLOSED
}
// 状态管理
public class Channel {
private ChannelState state = ChannelState.CONNECTED;
public void close() {
state = ChannelState.CLOSED; // 修改状态
}
}
20. 访问者模式 (Visitor)
作用:在对象结构中定义新操作,而无需修改结构本身。
Dubbo 实现:
NodeVisitor
访问者:通过访问者模式遍历服务目录节点。
public interface NodeVisitor {
void visit(DirectoryNode node);
void visit(RouterNode node);
}
// 具体访问者(ServiceVisitor)
public class ServiceVisitor implements NodeVisitor {
@Override
public void visit(DirectoryNode node) {
// 处理目录节点
}
@Override
public void visit(RouterNode node) {
// 处理路由节点
}
}
21. 解释器模式 (Interpreter)
作用:给定一种语言,定义其文法表示,并构建解释器来解释语言中的句子。
Dubbo 实现:
RouteScript
解释器:解释路由脚本(如条件表达式)。
public class RouteScript {
public boolean route(Invocation invocation, URL url) {
// 解析路由脚本(示例)
String condition = url.getParameter("condition");
return evaluate(condition, invocation); // 解释条件表达式
}
}
22. 迭代器模式 (Iterator)
作用:提供一种顺序访问集合元素的方法,而无需暴露其内部表示。
Dubbo 实现:
Directory
迭代器:通过迭代器遍历服务提供者列表。
public interface Directory<T> extends Node {
List<Invoker<T>> list(Invocation invocation);
}
// 具体实现(StaticDirectory)
public class StaticDirectory<T> implements Directory<T> {
private final List<Invoker<T>> invokers;
@Override
public List<Invoker<T>> list(Invocation invocation) {
return invokers; // 返回迭代器
}
}
23. 中介者模式 (Mediator)
作用:定义一个中介对象来封装一系列对象之间的交互。
Dubbo 实现:
Invoker
作为中介者:协调Protocol
、Filter
、Cluster
等组件之间的交互。
public class InvokerWrapper<T> implements Invoker<T> {
private final Invoker<T> invoker;
public InvokerWrapper(Invoker<T> invoker) {
this.invoker = invoker;
}
@Override
public Class<T> getInterface() {
return invoker.getInterface();
}
@Override
public Result invoke(Invocation invocation) {
return invoker.invoke(invocation); // 协调组件调用
}
}
总结
Dubbo 框架通过灵活运用 23 种设计模式,实现了高扩展性、低耦合性和灵活性。这些模式覆盖了对象创建、结构组织、行为交互等各个方面,是学习 Java 框架设计的经典案例。