Ruby块和迭代器有哪些设计模式
在Ruby中,块(Block)和迭代器(Iterator)是实现循环和数据处理的重要工具。以下是一些与块和迭代器相关的常用设计模式:
1. 适配器模式(Adapter Pattern)适配器模式用于将一个类的接口转换成客户端所期望的另一个接口形式。在Ruby中,块可以作为适配器使用,将一个集合适配成另一个集合的行为。
class ArrayAdapterdef initialize(array)@array = arrayenddef each(&block)@array.each(&block)endend# 使用示例array = [1, 2, 3]adapter = ArrayAdapter.new(array)adapter.each { |item| puts item }
2. 装饰器模式(Decorator Pattern)装饰器模式允许在不修改原始类的情况下,动态地添加新的功能。在Ruby中,块可以作为装饰器使用,为集合添加额外的操作。
class ArrayDecoratordef initialize(array)@array = arrayenddef each(&block)@array.each(&block)enddef log_each(&block)each do |item|block.call(item)puts "Logged: #{item}"endendend# 使用示例array = [1, 2, 3]decorator = ArrayDecorator.new(array)decorator.log_each { |item| puts item }
3. 组合模式(Composite Pattern)组合模式允许将对象组合成树形结构以表示“部分-整体”的层次结构。在Ruby中,块可以作为组合的一部分,处理集合中的元素。
class CompositeCollectionattr_accessor :elementsdef initialize@elements = []enddef add(element)@elements << elementenddef each(&block)@elements.each(&block)endend# 使用示例collection = CompositeCollection.newcollection.add("Element 1")collection.add("Element 2")collection.add("Element 3")collection.each { |element| puts element }
4. 迭代器模式(Iterator Pattern)迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露其内部的表示。在Ruby中,迭代器模式是内置的,通过each
方法实现。
class MyCollectiondef initialize@items = []enddef add(item)@items << itemenddef each(&block)@items.each(&block)endend# 使用示例collection = MyCollection.newcollection.add(1)collection.add(2)collection.add(3)collection.each { |item| puts item }
5. 策略模式(Strategy Pattern)策略模式定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。在Ruby中,块可以作为策略使用,实现不同的处理逻辑。
class Strategydef execute(&block)block.callendendclass AddStrategy < Strategydef execute(&block)block.call(1)endendclass MultiplyStrategy < Strategydef execute(&block)block.call(2)endend# 使用示例strategy = AddStrategy.newstrategy.execute { |x| puts x + 1 } # 输出 2strategy = MultiplyStrategy.newstrategy.execute { |x| puts x * 2 } # 输出 4
这些设计模式可以帮助你更灵活地使用块和迭代器,实现更复杂的功能和逻辑。