Smalltalk 语言 设计模式之责任链模式实战

Smalltalk阿木 发布于 2025-05-29 6 次阅读


责任链模式【1】实战:Smalltalk【2】 语言中的责任链模式实现

责任链模式是一种行为设计模式,允许将请求【3】的发送者和接收者解耦。这种模式创建了一个链,请求沿着这个链传递,直到有一个处理者【4】能够处理它。在Smalltalk语言中,我们可以通过对象和消息传递【5】来实现责任链模式。

责任链模式概述

责任链模式的主要目的是将请求的发送者和接收者解耦,并且允许在多个对象中传递一个请求,直到有一个对象处理它。这种模式在处理多个对象时非常有用,特别是当请求的处理者不确定或者动态变化【6】时。

在责任链模式中,通常有以下角色:

- Handler(处理者):定义处理请求的方法,并且包含一个指向下一个处理者的引用。
- ConcreteHandler(具体处理者【7】):实现具体的处理逻辑,并且决定是否将请求传递给链中的下一个处理者。
- Client(客户端【8】):创建链并发送请求。

Smalltalk 中的责任链模式实现

下面我们将使用Smalltalk语言来实现一个简单的责任链模式,假设我们有一个请求处理系统【9】,用于处理不同类型的请求。

1. 定义处理者接口

我们定义一个处理者接口,它包含一个方法来处理请求。

smalltalk
RequestHandler subclass: Handler
instanceVariableNames: 'nextHandler'
classVariableNames: 'nextHandler'
category: 'RequestHandler';

class>>initialize
nextHandler := nil.

class>>setNextHandler: aHandler
nextHandler := aHandler.

class>>handleRequest: aRequest
"Default implementation: do nothing and pass the request to the next handler."
self nextHandler handleRequest: aRequest.

2. 定义具体处理者

接下来,我们定义具体处理者,它们将实现具体的处理逻辑。

smalltalk
ConcreteHandler1 subclass: RequestHandler
instanceVariableNames: 'requestType'
category: 'RequestHandler';

class>>initialize: aRequestType
super initialize.
requestType := aRequestType.

class>>handleRequest: aRequest
"Handle requests of type 'requestType'."
if: [aRequest type = requestType]
then: [self handleSpecificRequest: aRequest]
else: [self passRequest].

class>>handleSpecificRequest: aRequest
"Implement the specific handling logic for this type of request."
"For example, print a message."
aRequest description printNl.

class>>passRequest
"Pass the request to the next handler in the chain."
self nextHandler handleRequest: aRequest.

3. 创建请求

我们还需要一个请求类来表示请求。

smalltalk
Request subclass: Object
instanceVariableNames: 'type description'
category: 'Request';

class>>initialize: aType and: aDescription
super initialize.
type := aType.
description := aDescription.

4. 客户端代码

我们创建客户端代码来构建责任链并发送请求。

smalltalk
| handler1 handler2 handler3 request |

handler1 := ConcreteHandler1 new initialize: 'type1'.
handler2 := ConcreteHandler1 new initialize: 'type2'.
handler3 := ConcreteHandler1 new initialize: 'type3'.

handler1 setNextHandler: handler2.
handler2 setNextHandler: handler3.

request := Request new initialize: 'type1' and: 'This is a type1 request'.
handler1 handleRequest: request.

request := Request new initialize: 'type2' and: 'This is a type2 request'.
handler1 handleRequest: request.

request := Request new initialize: 'type3' and: 'This is a type3 request'.
handler1 handleRequest: request.

request := Request new initialize: 'type4' and: 'This is a type4 request'.
handler1 handleRequest: request.

总结

我们使用Smalltalk语言实现了责任链模式。通过定义处理者接口和具体处理者,我们创建了一个请求处理链,客户端可以发送请求,请求会沿着链传递,直到找到能够处理它的处理者。这种模式在处理不确定或动态变化的请求时非常有用。

责任链模式在Smalltalk中的实现展示了Smalltalk强大的对象导向特性和消息传递机制。通过这种方式,我们可以轻松地构建复杂的系统,其中请求的处理逻辑可以灵活地扩展和修改。