Main Content

What are factory and singleton classes?

Archive - Originally posted on "The Horse's Mouth" - 2007-06-04 17:59:27 - Graham Ellis

Do you find some of the OO terminolgy baffling? Once you've learnt about constructors and methods, inheritance, overloading and polymorphism and statics, you might think you're there. Then someone mentions a "factory class" or a "singleton" ...

Fear not - factory and singleton classes are posh names for something you would naturally write anyway, applied to certain techniques so that they can be described in OO design texts, project specifications, and articles such as this.

A SINGLETON is a class for which only one object member ever exists; you can create a class that's a singleton by writing the constructor so that it returns a truely fresh object the first time you call it, and a reference to the same object should you call it again. We have an example (in Python, but it applies to any language in principle) here

A FACTORY is a class who's constructor returns an object which might be in one of several different classes, not necessarily including the class in which it is, in theory, the contsructor. I could, for example, have a base class called "accom" for accommodation, subclassed to "hotel" and "campsite". If calls to the "accom" constructor return a hotel or a campsite (depending on constructor parameters), then that accom class is a factory. We have an example of a factory (in PHP, but it applies to any language in principle) here. There's also an exanple in Perl ... the class containing the factory method is available here, sample code that calls it here and the other class that may be built here