design-patterns-ruby

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<objective> Provide Ruby implementations and guidance for all 23 GoF design patterns. Help agents identify which pattern solves a given problem and implement it idiomatically in Ruby. </objective>
<quick_start> <pattern_selection> Object Creation Problems → Creational Patterns
  • Decouple creation from usage → Factory Method
  • Families of related objects → Abstract Factory
  • Complex objects with many params → Builder
  • Clone without concrete class dependency → Prototype
  • Single shared instance → Singleton
Structural Problems → Structural Patterns
  • Incompatible interfaces → Adapter
  • Multiple independent dimensions → Bridge
  • Tree structures treated uniformly → Composite
  • Add behavior dynamically → Decorator
  • Simplify complex subsystems → Facade
  • Memory with many similar objects → Flyweight
  • Access control/logging/caching → Proxy
Behavioral Problems → Behavioral Patterns
  • Multiple handlers in sequence → Chain of Responsibility
  • Decouple UI from business logic → Command
  • Traverse without exposing internals → Iterator
  • Reduce chaotic dependencies → Mediator
  • Undo/restore functionality → Memento
  • Notify about state changes → Observer
  • Behavior varies by state → State
  • Switch algorithms at runtime → Strategy
  • Algorithm skeleton with custom steps → Template Method
  • Operations on complex structures → Visitor </pattern_selection>
<ruby_abstract_method> Ruby doesn't have built-in abstract methods. Use:
ruby
def abstract_method
  raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
</ruby_abstract_method> </quick_start>
<when_to_use> Use this skill when encountering:
  • "How do I create objects without specifying exact classes?" → Factory Method/Abstract Factory
  • "Constructor has too many parameters" → Builder
  • "Need to copy objects without knowing their concrete type" → Prototype
  • "Ensure only one instance exists" → Singleton
  • "Legacy class interface doesn't match what I need" → Adapter
  • "Class explosion from combining multiple features" → Bridge
  • "Work with tree/hierarchy uniformly" → Composite
  • "Add features without modifying class" → Decorator
  • "Simplify interaction with complex library" → Facade
  • "Too many similar objects consuming memory" → Flyweight
  • "Control access/add logging to object" → Proxy
  • "Request goes through chain of handlers" → Chain of Responsibility
  • "Need undo/redo or queue operations" → Command
  • "Custom iteration over collection" → Iterator
  • "Components too tightly coupled" → Mediator
  • "Save and restore object state" → Memento
  • "Notify multiple objects of changes" → Observer
  • "Object behavior depends on state" → State
  • "Swap algorithms at runtime" → Strategy
  • "Subclasses customize algorithm steps" → Template Method
  • "Add operations to class hierarchy" → Visitor </when_to_use>
<pattern_quick_reference> <creational> Factory Method - Define interface for creation, let subclasses decide type
ruby
class Creator
  def factory_method
    raise NotImplementedError
  end

  def operation
    product = factory_method
    "Working with #{product.operation}"
  end
end

class ConcreteCreator < Creator
  def factory_method
    ConcreteProduct.new
  end
end
File:
Ruby/src/factory_method/conceptual/main.rb
Singleton (thread-safe)
ruby
class Singleton
  @instance_mutex = Mutex.new
  private_class_method :new

  def self.instance
    return @instance if @instance
    @instance_mutex.synchronize { @instance ||= new }
    @instance
  end
end
File:
Ruby/src/singleton/conceptual/thread_safe/main.rb
See references/creational-patterns.md for Abstract Factory, Builder, Prototype. </creational>
<structural> **Decorator** - Wrap objects to add behavior dynamically ```ruby class Decorator < Component def initialize(component) @component = component end
def operation @component.operation end end
class ConcreteDecorator < Decorator def operation "Decorated(#{@component.operation})" end end
<objective> 提供所有23种GoF设计模式的Ruby实现与指导。帮助开发者确定哪种模式能解决特定问题,并以Ruby的惯用方式实现该模式。 </objective>
<quick_start> <pattern_selection> 对象创建类问题 → 创建型模式
  • 将对象创建与使用解耦 → Factory Method
  • 相关对象家族的创建 → Abstract Factory
  • 含多个参数的复杂对象创建 → Builder
  • 无需依赖具体类即可克隆对象 → Prototype
  • 单一共享实例 → Singleton
结构类问题 → 结构型模式
  • 适配不兼容的接口 → Adapter
  • 处理多个独立维度的变化 → Bridge
  • 统一处理树形结构 → Composite
  • 动态添加对象行为 → Decorator
  • 简化复杂子系统的交互 → Facade
  • 大量相似对象的内存优化 → Flyweight
  • 对象的访问控制/日志/缓存 → Proxy
行为类问题 → 行为型模式
  • 让请求依次经过多个处理器 → Chain of Responsibility
  • 将UI与业务逻辑解耦 → Command
  • 遍历集合而不暴露内部结构 → Iterator
  • 减少混乱的依赖关系 → Mediator
  • 实现撤销/恢复功能 → Memento
  • 状态变更时通知相关对象 → Observer
  • 对象行为随状态变化 → State
  • 运行时切换算法 → Strategy
  • 定义算法骨架,子类实现自定义步骤 → Template Method
  • 对复杂结构执行操作 → Visitor </pattern_selection>
<ruby_abstract_method> Ruby没有内置的抽象方法,可以使用:
ruby
def abstract_method
  raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
</ruby_abstract_method> </quick_start>
<when_to_use> 在以下场景中使用本技能:
  • "如何在不指定具体类的情况下创建对象?" → Factory Method/Abstract Factory
  • "构造函数参数过多" → Builder
  • "需要在不知道具体类型的情况下复制对象" → Prototype
  • "确保仅存在一个实例" → Singleton
  • "遗留类的接口不符合需求" → Adapter
  • "组合多个功能导致类爆炸" → Bridge
  • "统一处理树形/层级结构" → Composite
  • "无需修改类即可添加功能" → Decorator
  • "简化与复杂库的交互" → Facade
  • "大量相似对象占用过多内存" → Flyweight
  • "控制对象访问/添加日志功能" → Proxy
  • "请求需要经过多个处理器链" → Chain of Responsibility
  • "需要实现撤销/重做或操作队列" → Command
  • "自定义集合的遍历方式" → Iterator
  • "组件间耦合度过高" → Mediator
  • "保存与恢复对象状态" → Memento
  • "状态变更时通知多个对象" → Observer
  • "对象行为依赖其内部状态" → State
  • "运行时切换算法" → Strategy
  • "子类自定义算法步骤" → Template Method
  • "为类层级添加操作" → Visitor </when_to_use>
<pattern_quick_reference> <creational> Factory Method - 定义对象创建的接口,由子类决定具体创建的类型
ruby
class Creator
  def factory_method
    raise NotImplementedError
  end

  def operation
    product = factory_method
    "Working with #{product.operation}"
  end
end

class ConcreteCreator < Creator
  def factory_method
    ConcreteProduct.new
  end
end
File:
Ruby/src/factory_method/conceptual/main.rb
Singleton(线程安全)
ruby
class Singleton
  @instance_mutex = Mutex.new
  private_class_method :new

  def self.instance
    return @instance if @instance
    @instance_mutex.synchronize { @instance ||= new }
    @instance
  end
end
File:
Ruby/src/singleton/conceptual/thread_safe/main.rb
更多内容请查看 references/creational-patterns.md 中的Abstract Factory、Builder、Prototype。 </creational>
<structural> **Decorator** - 包装对象以动态添加行为 ```ruby class Decorator < Component def initialize(component) @component = component end
def operation @component.operation end end
class ConcreteDecorator < Decorator def operation "Decorated(#{@component.operation})" end end

Stack decorators

堆叠装饰器

decorated = DecoratorB.new(DecoratorA.new(ConcreteComponent.new))
File: `Ruby/src/decorator/conceptual/main.rb`

**Adapter** - Convert interface to expected format
```ruby
class Adapter < Target
  def initialize(adaptee)
    @adaptee = adaptee
  end

  def request
    "Adapted: #{@adaptee.specific_request}"
  end
end
File:
Ruby/src/adapter/conceptual/main.rb
See references/structural-patterns.md for Bridge, Composite, Facade, Flyweight, Proxy. </structural>
<behavioral> **Strategy** - Swap algorithms at runtime ```ruby class Context attr_writer :strategy
def initialize(strategy) @strategy = strategy end
def execute @strategy.do_algorithm(data) end end
decorated = DecoratorB.new(DecoratorA.new(ConcreteComponent.new))
File: `Ruby/src/decorator/conceptual/main.rb`

**Adapter** - 将接口转换为预期格式
```ruby
class Adapter < Target
  def initialize(adaptee)
    @adaptee = adaptee
  end

  def request
    "Adapted: #{@adaptee.specific_request}"
  end
end
File:
Ruby/src/adapter/conceptual/main.rb
更多内容请查看 references/structural-patterns.md 中的Bridge、Composite、Facade、Flyweight、Proxy。 </structural>
<behavioral> **Strategy** - 运行时切换算法 ```ruby class Context attr_writer :strategy
def initialize(strategy) @strategy = strategy end
def execute @strategy.do_algorithm(data) end end

Switch strategy at runtime

运行时切换策略

context = Context.new(StrategyA.new) context.strategy = StrategyB.new
File: `Ruby/src/strategy/conceptual/main.rb`

**Observer** - Notify subscribers of state changes
```ruby
class Subject
  def initialize
    @observers = []
  end

  def attach(observer)
    @observers << observer
  end

  def detach(observer)
    @observers.delete(observer)
  end

  def notify
    @observers.each { |observer| observer.update(self) }
  end
end
File:
Ruby/src/observer/conceptual/main.rb
State - Object behavior changes based on internal state
ruby
class Context
  attr_accessor :state

  def transition_to(state)
    @state = state
    @state.context = self
  end

  def request
    @state.handle
  end
end
File:
Ruby/src/state/conceptual/main.rb
See references/behavioral-patterns.md for Chain of Responsibility, Command, Iterator, Mediator, Memento, Template Method, Visitor. </behavioral> </pattern_quick_reference>
<ruby_idioms> <deep_copy> For Prototype pattern, use Marshal for deep copying:
ruby
Marshal.load(Marshal.dump(object))
</deep_copy>
<thread_safety> For Singleton and shared resources, use Mutex:
ruby
@mutex = Mutex.new
@mutex.synchronize { @instance ||= new }
</thread_safety>
<private_constructor> For Singleton pattern:
ruby
private_class_method :new
</private_constructor>
<accessors> - `attr_reader :name` - read-only - `attr_writer :name` - write-only - `attr_accessor :name` - read/write </accessors>
<type_docs> Use YARD-style documentation:
ruby
undefined
context = Context.new(StrategyA.new) context.strategy = StrategyB.new
File: `Ruby/src/strategy/conceptual/main.rb`

**Observer** - 状态变更时通知订阅者
```ruby
class Subject
  def initialize
    @observers = []
  end

  def attach(observer)
    @observers << observer
  end

  def detach(observer)
    @observers.delete(observer)
  end

  def notify
    @observers.each { |observer| observer.update(self) }
  end
end
File:
Ruby/src/observer/conceptual/main.rb
State - 对象行为随内部状态变化
ruby
class Context
  attr_accessor :state

  def transition_to(state)
    @state = state
    @state.context = self
  end

  def request
    @state.handle
  end
end
File:
Ruby/src/state/conceptual/main.rb
更多内容请查看 references/behavioral-patterns.md 中的Chain of Responsibility、Command、Iterator、Mediator、Memento、Template Method、Visitor。 </behavioral> </pattern_quick_reference>
<ruby_idioms> <deep_copy> 对于Prototype模式,可使用Marshal进行深拷贝:
ruby
Marshal.load(Marshal.dump(object))
</deep_copy>
<thread_safety> 对于Singleton和共享资源,使用Mutex保证线程安全:
ruby
@mutex = Mutex.new
@mutex.synchronize { @instance ||= new }
</thread_safety>
<private_constructor> 对于Singleton模式:
ruby
private_class_method :new
</private_constructor>
<accessors> - `attr_reader :name` - 只读 - `attr_writer :name` - 只写 - `attr_accessor :name` - 读写 </accessors>
<type_docs> 使用YARD风格的文档注释:
ruby
undefined

@param [String] value

@param [String] value

@return [Boolean]

@return [Boolean]

def method(value) end

</type_docs>
</ruby_idioms>

<running_examples>

```bash
ruby Ruby/src/<pattern>/conceptual/main.rb
def method(value) end

</type_docs>
</ruby_idioms>

<running_examples>

```bash
ruby Ruby/src/<pattern>/conceptual/main.rb

Examples:

示例:

ruby Ruby/src/singleton/conceptual/thread_safe/main.rb ruby Ruby/src/observer/conceptual/main.rb ruby Ruby/src/strategy/conceptual/main.rb ruby Ruby/src/decorator/conceptual/main.rb

Requires Ruby 3.2+.
</running_examples>

<detailed_references>

- [references/creational-patterns.md](references/creational-patterns.md) - Factory Method, Abstract Factory, Builder, Prototype, Singleton
- [references/structural-patterns.md](references/structural-patterns.md) - Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
- [references/behavioral-patterns.md](references/behavioral-patterns.md) - Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor
</detailed_references>

<success_criteria>

- Pattern correctly solves the identified design problem
- Ruby idioms used appropriately (NotImplementedError, Marshal, Mutex)
- Code follows Ruby conventions (snake_case, attr_* accessors)
- Example runs without errors via `ruby Ruby/src/<pattern>/conceptual/main.rb`
</success_criteria>
ruby Ruby/src/singleton/conceptual/thread_safe/main.rb ruby Ruby/src/observer/conceptual/main.rb ruby Ruby/src/strategy/conceptual/main.rb ruby Ruby/src/decorator/conceptual/main.rb

需要Ruby 3.2及以上版本。
</running_examples>

<detailed_references>

- [references/creational-patterns.md](references/creational-patterns.md) - Factory Method、Abstract Factory、Builder、Prototype、Singleton
- [references/structural-patterns.md](references/structural-patterns.md) - Adapter、Bridge、Composite、Decorator、Facade、Flyweight、Proxy
- [references/behavioral-patterns.md](references/behavioral-patterns.md) - Chain of Responsibility、Command、Iterator、Mediator、Memento、Observer、State、Strategy、Template Method、Visitor
</detailed_references>

<success_criteria>

- 所选模式能正确解决已识别的设计问题
- 恰当使用Ruby惯用技巧(如NotImplementedError、Marshal、Mutex)
- 代码遵循Ruby规范(snake_case命名、attr_*访问器)
- 示例可通过 `ruby Ruby/src/<pattern>/conceptual/main.rb` 命令无错误运行
</success_criteria>