
代码示例:
在 Ruby 中,代理模式(Proxy Pattern)和装饰模式(Decorator Pattern)是两种常见的结构型设计模式。它们都用于扩展对象的功能,但实现方式和应用场景有所不同。以下是两种模式的详细代码实例。
1. 代理模式(Proxy Pattern)
代理模式是一种结构型设计模式,它通过创建一个代理对象来控制对实际对象的访问。代理对象可以添加一层间接层,从而在不改变实际对象代码的情况下,为实际对象添加额外的功能,例如权限控制、懒加载、缓存等。
示例场景
假设我们有一个 RealSubject 类,表示一个实际对象,它有一个 request 方法。我们希望通过代理对象来控制对 RealSubject 的访问,并在访问时添加一些额外的逻辑,例如日志记录。
代码实现
# 实际对象
class RealSubject
def request
puts "RealSubject: Handling request."
end
end
# 代理对象
class Proxy
def initialize(real_subject)
@real_subject = real_subject
end
def request
if access_allowed?
@real_subject.request
log_access
end
end
private
def access_allowed?
# 模拟权限检查
puts "Proxy: Logging the time of request."
true
end
def log_access
# 模拟日志记录
puts "Proxy: Logging the request."
end
end
# 使用代理
real_subject = RealSubject.new
proxy = Proxy.new(real_subject)
proxy.request
输出结果
Proxy: Logging the time of request.
RealSubject: Handling request.
Proxy: Logging the request.
2. 装饰模式(Decorator Pattern)
装饰模式是一种结构型设计模式,它通过创建一个装饰类来动态地为对象添加额外的功能。装饰类通常继承自目标类或实现与目标类相同的接口,从而可以在不改变目标类代码的情况下,扩展其功能。
示例场景
假设我们有一个 Component 接口,表示一个可以被装饰的对象。我们有两个具体的组件类 ConcreteComponentA 和 ConcreteComponentB。我们希望通过装饰类 Decorator 来动态地为这些组件添加额外的功能。
代码实现
# 组件接口
class Component
def operation
raise NotImplementedError, "You should implement the operation method."
end
end
# 具体组件A
class ConcreteComponentA < Component
def operation
puts "ConcreteComponentA: Operation."
end
end
# 具体组件B
class ConcreteComponentB < Component
def operation
puts "ConcreteComponentB: Operation."
end
end
# 装饰类
class Decorator < Component
def initialize(component)
@component = component
end
def operation
@component.operation
end
end
# 具体装饰类A
class ConcreteDecoratorA < Decorator
def operation
super
added_behavior
end
private
def added_behavior
puts "ConcreteDecoratorA: Added behavior."
end
end
# 具体装饰类B
class ConcreteDecoratorB < Decorator
def operation
super
added_behavior
end
private
def added_behavior
puts "ConcreteDecoratorB: Added behavior."
end
end
# 使用装饰
component_a = ConcreteComponentA.new
decorated_a = ConcreteDecoratorA.new(component_a)
decorated_a.operation
component_b = ConcreteComponentB.new
decorated_b = ConcreteDecoratorB.new(component_b)
decorated_b.operation
输出结果
ConcreteComponentA: Operation.
ConcreteDecoratorA: Added behavior.
ConcreteComponentB: Operation.
ConcreteDecoratorB: Added behavior.
总结
- 代理模式通过代理对象控制对实际对象的访问,适用于需要在访问时添加额外逻辑的场景。
- 装饰模式通过装饰类动态地为对象添加额外功能,适用于需要动态扩展对象功能的场景。
这两种模式在实际开发中都非常有用,可以根据具体需求选择合适的模式来实现功能扩展。
更多技术文章见公众号: 大城市小农民


被折叠的 条评论
为什么被折叠?



