设计模式是一种解决特定问题的经过验证的解决方案。它们通常是在软件工程实践中形成的最佳实践,并且可以在多种不同的场景中使用。本章将介绍一些在 Ruby 中常见的设计模式,包括但不限于单例模式、工厂模式、策略模式、观察者模式和装饰器模式。
单例模式
单例模式确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。这在需要频繁访问相同对象的情况下非常有用。
使用场景
当你需要确保在整个应用程序中只存在一个特定类型的实例时,可以使用单例模式。例如,配置管理、日志记录等。
实现方式
// www.javascriptcn.com code example
class Singleton
@instance = nil
def self.instance
@instance ||= new
end
private_class_method :new
def show_message
"Hello, World!"
end
end
# 使用单例类
puts Singleton.instance.show_message # 输出: Hello, World!工厂模式
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需指定具体的类。通过使用工厂方法,我们可以在不修改客户端代码的情况下更改创建的对象类型。
使用场景
当你想要控制对象的创建过程,或者希望将对象的创建与使用分离时,可以使用工厂模式。
实现方式
// www.javascriptcn.com code example
class CarFactory
def self.create_car(type)
case type
when :sedan then Sedan.new
when :suv then Suv.new
else raise ArgumentError, "Unknown car type"
end
end
end
class Sedan
def drive
"Driving a sedan"
end
end
class Suv
def drive
"Driving an SUV"
end
end
# 使用工厂类
puts CarFactory.create_car(:sedan).drive # 输出: Driving a sedan
puts CarFactory.create_car(:suv).drive # 输出: Driving an SUV策略模式
策略模式是一种行为设计模式,它允许你定义一系列算法,并将每个算法封装起来,使它们可以互换。策略模式让你的算法独立于使用它的客户。
使用场景
当你有很多类似的方法,但这些方法的行为略有不同,你可以使用策略模式来组织它们。
实现方式
// www.javascriptcn.com code example
class Order
attr_accessor :total, :discount_strategy
def initialize(total, discount_strategy)
@total = total
@discount_strategy = discount_strategy
end
def discount
discount_strategy.calculate(self)
end
def final_total
total - discount
end
end
class NoDiscount
def calculate(order)
0
end
end
class ThirtyPercentDiscount
def calculate(order)
order.total * 0.3
end
end
# 使用策略
order = Order.new(100, ThirtyPercentDiscount.new)
puts order.final_total # 输出: 70观察者模式
观察者模式是一种行为设计模式,它允许你定义一个订阅机制,在对象事件发生时通知多个“观察”该对象的其他对象。
使用场景
当你想要在某个对象的状态发生变化时自动更新其他对象时,可以使用观察者模式。
实现方式
// www.javascriptcn.com code example
class Subject
def initialize
@observers = []
end
def add_observer(observer)
@observers << observer
end
def remove_observer(observer)
@observers.delete(observer)
end
def notify_observers
@observers.each { |observer| observer.update }
end
end
class Observer
def update
puts "Observer notified"
end
end
subject = Subject.new
observer1 = Observer.new
observer2 = Observer.new
subject.add_observer(observer1)
subject.add_observer(observer2)
subject.notify_observers # 输出:
# Observer notified
# Observer notified装饰器模式
装饰器模式是一种结构型设计模式,它允许你在不影响其他对象的情况下,动态地给一个对象添加新的功能。
使用场景
当你想要扩展一个对象的功能,而又不想修改其原始代码时,可以使用装饰器模式。
实现方式
// www.javascriptcn.com code example
class Component
def operation
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
end
class ConcreteComponent < Component
def operation
"ConcreteComponent"
end
end
class Decorator < Component
def initialize(component)
@component = component
end
def operation
@component.operation
end
end
class ConcreteDecoratorA < Decorator
def operation
"ConcreteDecoratorA(#{super})"
end
end
class ConcreteDecoratorB < Decorator
def operation
"ConcreteDecoratorB(#{super})"
end
end
# 使用装饰器
simple = ConcreteComponent.new
puts simple.operation # 输出: ConcreteComponent
decorated = ConcreteDecoratorA.new(simple)
puts decorated.operation # 输出: ConcreteDecoratorA(ConcreteComponent)
decorated2 = ConcreteDecoratorB.new(decorated)
puts decorated2.operation # 输出: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))以上是几种常见设计模式在 Ruby 中的实现方式。通过理解和应用这些设计模式,可以让你的代码更加模块化、易于维护和扩展。