Singleton is common for every coder. It provide only instance of class.
class SimpleLogger
# Lots of code deleted...
@@instance = SimpleLogger.new
def self.instance
return @@instance
end
private_class_method :new
end
In ruby we can use Singleton Module, it is lazy instantiation
require 'singleton'
class SimpleLogger
include Singleton
# Lots of code deleted...
end
And we can use to implement eager instantiation
class SimpleLogger
# Lots of code deleted...
@@instance = SimpleLogger.new
# Lots of code deleted...
end
There are some other way to implement the singleton pattern:
$logger = SimpleLogger.new
or
Logger = SimpleLogger.new
The deficiencies are as below:
First, if you use a global variable or a constant for this purpose, there is no way to delay the creation of the singleton object until you need it. The global variable or constant is there from the moment we first set it.
Second, neither of these techniques does anything to prevent someone from creating a second or third instance of your supposedly singleton class.
分享到:
相关推荐
Addison.Wesley.Design.Patterns.in.Ruby.Dec.2007 高清PDF英文版
《Design Patterns in Ruby Dec 2007》是关于Ruby编程语言中设计模式的一份珍贵资料,这份2007年发布的PDF文档深入探讨了如何在Ruby语言中应用经典的设计模式。设计模式是软件工程中经过实践证明的有效解决方案模板...
design pattern in C# language
Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design English | PDF| 2018 | 312 Pages | ISBN : 1484236025Design Patterns in Modern C++: Reusable Approaches for Object...
Too often design patterns are explained using tricky concepts, when in fact they are easy to use and can enrich your everyday development. Design Patterns in ...
Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....
Alan Ezust在其著作《An Introduction to Design Patterns in C++ with Qt™, 2nd Edition》中探讨了设计模式的这一概念,并且在Qt框架的基础上讲解了如何在C++项目中应用这些设计模式。 C++是一种高性能、多范式的...
App Architecture: iOS Application Design Patterns in Swift 包含Source code 有钱请支持正版 没钱请默默学习 原书地址: https://www.objc.io/books/app-architecture 中文原书地址: ...
Data Structures And Algorithms With Object-oriented Design Patterns In Java.chm
Use creational patterns of builder, factories, prototype and singleton Implement structural patterns such as adapter, bridge, decorator, facade and more Work with the behavioral patterns such as ...
Design Patterns in Java(2nd) 英文epub 第2版 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
and applications that run on various software and hardware platforms with little or no change in the underlying codebase, while still being a native application with native capabilities and speed....
Design Patterns in Modern C++ Reusable Approaches for Object-Oriented Software Design 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书