
代码示例:
单例模式是一种常用的设计模式,其核心思想是确保一个类只有一个实例,并提供一个全局访问点。在 Ruby 中,单例模式可以通过多种方式实现,以下将详细介绍几种常见的实现方法及其应用场景。
1. 基础单例模式实现
最简单的单例模式实现是通过隐藏构造函数并提供一个静态的构建方法来控制实例的创建。
class Singleton
@instance = new
private_class_method :new
def self.instance
@instance
end
def some_business_logic
# 业务逻辑代码
end
end
# 客户端代码
s1 = Singleton.instance
s2 = Singleton.instance
if s1.equal?(s2)
puts 'Singleton works, both variables contain the same instance.'
else
puts 'Singleton failed, variables contain different instances.'
end
2. 线程安全的单例模式
在多线程环境中,基础单例模式可能会导致多个线程同时调用构建方法,从而创建多个实例。为了避免这种情况,需要在创建首个单例对象时对线程进行同步。
class Singleton
attr_reader :value
@instance_mutex = Mutex.new
private_class_method :new
def initialize(value)
@value = value
end
def self.instance(value)
return @instance if @instance
@instance_mutex.synchronize do
@instance ||= new(value)
end
@instance
end
def some_business_logic
# 业务逻辑代码
end
end
def test_singleton(value)
singleton = Singleton.instance(value)
puts singleton.value
end
puts "If you see the same value, then singleton was reused (yay!)\n"\
"If you see different values, then 2 singletons were created (booo!)\n\n"\
"RESULT:\n\n"
process1 = Thread.new { test_singleton('FOO') }
process2 = Thread.new { test_singleton('BAR') }
process1.join
process2.join
3. 使用 Ruby 标准库中的 Singleton 模块
Ruby 标准库提供了一个 Singleton 模块,可以非常方便地实现单例模式。
require 'singleton'
class Logger
include Singleton
DEBUG = 0
INFO = 1
ERROR = 2
NOTHING = 3
LEVEL = DEBUG
def debug(msg)
puts msg if DEBUG >= LEVEL
end
def info(msg)
puts msg if INFO >= LEVEL
end
def error(msg)
puts msg if ERROR >= LEVEL
end
end
# 使用单例
logger = Logger.instance
logger.debug("Hello World")
4. 单例模式的应用场景
单例模式在实际开发中有很多应用场景,例如日志记录器、配置管理器等。以日志记录器为例,通常希望整个应用程序中只有一个日志记录器实例,这样可以方便地控制日志的输出。
5. 单例模式的优缺点
- 优点:
- 确保全局只有一个实例,避免资源浪费。
- 提供全局访问点,方便使用。
- 缺点:
- 违反单一职责原则,将实例化逻辑与业务逻辑混合。
- 增加代码的耦合度,不利于单元测试。
单例模式在 Ruby 中的实现和应用非常灵活,但需要谨慎使用,以避免引入不必要的复杂性和耦合度。
关键词指令
- 单例模式的优缺点
- 单例模式的线程安全问题
- 单例模式的实际应用案例
更多技术文章见公众号: 大城市小农民

14

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



