关于单例模式的概念,这里就不多说了。
Ruby如何实现,先看下面的代码:
- class MyLogger
- private_class_method :new
- @@logger = nil
- def MyLogger.create
- @@logger = new unless @@logger
- @@logger
- end
- end
- log1 = MyLogger.create
- log2 = MyLogger.create
- if log1 == log2
- puts "same"
- else
- puts "different"
- end
运行后输出:same
可以作如下的测试:
- class MyLogger
- #private_class_method :new
- @@logger = nil
- def MyLogger.create
- @@logger = new unless @@logger
- @@logger
- end
- end
- #log1 = MyLogger.create
- #log2 = MyLogger.create
- log1 = MyLogger.new
- log2 = MyLogger.new
- if log1 == log2
- puts "same"
- else
- puts "different"
- end
输出:different