ruby学习笔记系列(3)

经典Singletons

Sometimes you want to override the default way in which Ruby creates objects. As an
example, let’s look at our jukebox. Because we’ll have many jukeboxes, spread all over
the country, we want to make maintenance as easy as possible. Part of the requirement
is to log everything that happens to a jukebox: the songs played, the money received,
the strange fluids poured into it, and so on. Because we want to reserve the network
bandwidth for music, we’ll store these log files locally. This means we’ll need a class
that handles logging. However, we want only one logging object per jukebox, and we
want that object to be shared among all the other objects that use it.
Enter the Singleton pattern, documented in Design Patterns [GHJV95]. We’ll arrange
things so that the only way to create a logging object is to call MyLogger.create, and
we’ll ensure that only one logging object is ever created.
class MyLogger
private_class_method :new
@@logger = nil
def MyLogger.create
@@logger = new unless @@logger
@@logger
end
end
By making MyLogger’s new method private, we prevent anyone from creating a logging
object using the conventional constructor. Instead, we provide a class method,
MyLogger.create. This method uses the class variable @@logger to keep a reference
to a single instance of the logger, returning that instance every time it is called.3 We
can check this by looking at the object identifiers the method returns.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值