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.

你可能感兴趣的:(Ruby)