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
Some other articles
Y112 - Objects - Intermediate Nesting decorators Defining an object that is a modified standard type in Python with in Python - examples of use, and of defining your own context Object and Static methods - what is the difference; example in Python 3 Setting up and tearing down with the Python with keyword Deciding whether to use parameters, conditional statements or subclasses Spike solution, refactoring into encapsulated object methods - good design practise A good example of recursion - a real use in Python Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Python base and inherited classes, test harness and unit testing - new examples Python Properties - how and why Really Simple Class and Inheritance example in Python Inheritance, Composition and Associated objects - when to use which - Python example Backquote, backtic, str and repr in Python - conversion object to string Metaclasses (Python) and Metatables (Lua) Static variables in functions - and better ways using objects A demonstration of how many Python facilities work together A list of special method and attribute names in Python Python - some common questions answered in code examples Defining static methods in Python Should Python classes each be in their own file? The Light bulb moment when people see how Object Orientation works in real use Python decorators - your own, staticmethod and classmethod Mixins example in Python Multiple inheritance in Python - complete working example The Multiple Inheritance Conundrum, interfaces and mixins Methods that run on classes (static methods) in Python How do I set up a constant in Python? TypeError: super() argument 1 must be type, not classobj (Python) Python - fresh examples of all the fundamentals Calling base class constructors Equality, sameness and identity - Python Using a utility method to construct objects of different types - Python Python - formatting objects This article __new__ v __init__ - python constructor alternatives? Practical polymorphism in action Pieces of Python Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML Class, static and unbound variables Overloading of operators on standard objects in Python Using a Python dictionary as a holder of object attributes R108 - More Classes and Objects Testing your new class - first steps with cucumber Build up classes into applications sharing data types in Ruby Where does Ruby load modules from, and how to load from current directory Changing what operators do on objects - a comparison across different programming languages Standard methods available on all objects in Ruby Private, Protected, Public in Ruby. What about interfaces and abstract classes in Ruby? Why you should use objects even for short data manipulation programs in Ruby Ruby - a training example that puts many language elements together to demonstrate the whole Ruby training - some fresh examples for string handling applications Changing a class later on - Ruby Private and Public - and things between Ruby - examples of regular expressions, inheritance and polymorphism What is a factory method and why use one? - Example in Ruby The Multiple Inheritance Conundrum, interfaces and mixins Object Oriented Ruby - new examples Direct access to object variable (attributes) in Ruby Defining a static method - Java, Python and Ruby Tips for writing a test program (Ruby / Python / Java) Ruby objects - a primer Ruby - is_a? v instance_of? - what is the difference? Object Orientation in Ruby - intermediate examples Some Ruby programming examples from our course This article Think about your design even if you don't use full UML MTBF of coffee machines Q907 - Object Orientation: Design Techniques Associative objects - one object within another. Spike solution, refactoring into encapsulated object methods - good design practise The spirit of Java - delegating to classes Test driven development, and class design, from first principles (using C++) Using object orientation for non-physical objects Teaching OO - how to avoid lots of window switching early on Storing your intermediate data - what format should you you choose? Inheritance, Composition and Associated objects - when to use which - Python example From Structured to Object Oriented Programming. Rooms ready for guests - each time, every time, thanks to good system design When you should use Object Orientation even in a short program - Python example Spike solutions and refactoring - a Python example Why you should use objects even for short data manipulation programs in Ruby Designing your application - using UML techniques Your PHP website - how to factor and refactor to reduce growing pains Ruby - a training example that puts many language elements together to demonstrate the whole Object Oriented Programming for Structured Programmers - conversion training Comments in and on Perl - a case for extreme OO programming What is a factory method and why use one? - Example in Ruby Turning an exercise into the real thing with extreme programming Should Python classes each be in their own file? Program for reliability and efficiency - do not duplicate, but rather share and re-use Relationships between Java classes - inheritance, packaging and others The Light bulb moment when people see how Object Orientation works in real use Containment, Associative Objects, Inheritance, packages and modules What is a factory? The Multiple Inheritance Conundrum, interfaces and mixins Plan your application before you start Simples Object Oriented programming - a practical design example Planning! Designing a heirarcy of classes - getting inheritance right When should I use OO techniques? Teaching Object Oriented Java with Students and Ice Cream Object Oriented Tcl Object Oriented Programming in Perl - Course Object Relation Mapping (ORM) This article Maintainable code - some positive advice Build on what you already have with OO Comparison of Object Oriented Philosophy - Python, Java, C++, Perl The Fag Packet Design Methodology Think about your design even if you don't use full UML Design - one name, one action Introduction to Object Oriented Programming Tapping in on resources OO - real benefits P218 - More Objects Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Using object orientation for non-physical objects Perl design patterns example Building an object based on another object in Perl Perl - calls to methods that use => - what do they mean? What do I mean when I add things in Perl? Learning Object Orientation in Perl through bananas and perhaps Moose Making Perl class definitions more conventional and shorter Some more advanced Perl examples from a recent course Different perl examples - some corners I rarely explore Igloos melt in the summer, but houses do not The Multiple Inheritance Conundrum, interfaces and mixins Calculation within objects - early, last minute, or cached? Operator overloading - redefining addition and other Perl tricks Nuclear Physics comes to our web site Calling base class constructors Factory method example - Perl Example of OO in Perl Object Oriented Programming in Perl - Course Perl for Larger Projects - Object Oriented Perl This article -> , >= and => in Perl Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML NOT Gone phishing Changing @INC - where Perl loads its modules Packages in packages in Perl When to bless a Perl variable Bellringing and Programming and Objects and Perl J710 - Extending Classes and More Objects - from physical to virtual or abstract - Java Java Inheritance example - group of classes - step by step Philosophy behind object design - and how I applied in to a Java example Changing what operators do on objects - a comparison across different programming languages Splitting out code into name blocks for clarity and reusability What is a universal superclass? Java / Perl / Python / Other OO languages What methods are available on this Java object? Tips for writing a test program (Ruby / Python / Java) Abstract classes, Interfaces, PHP and Java Abstract Classes - Java Calling base class constructors Java - a demonstration of inheritance on just one page Teaching Object Oriented Java with Students and Ice Cream Java - using super to call a method in the parent class An example of Java Inheritance from scratch This article Final, Finally and Finalize - three special words in Java Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML H108 - Objects in PHP Associative objects - one object within another. Caching results in an object for efficiency - avoiding re-calculation Singleton design pattern - examples and uses Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Learning about Object Orientation in PHP - a new set of examples stdClass in PHP - using an object rather than an associative array Objects in PHP - Revision Caching Design Patterns Copying, duplicating, cloning an object in PHP Autoload in PHP How do classes relate to each other? Associated Classes Design Patterns - what are they? Why use them? Designing your application - using UML techniques Computer Graphics in PHP - World (incoming data) to Pixel (screen) conversion Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON Private and Public - and things between Getting the OO design write - with PHP a example Does copying a variable duplicate the contents? PHP - Object Oriented Design in use What is a factory? The Multiple Inheritance Conundrum, interfaces and mixins Static class members in PHP - a documented example Object Oriented Programming in PHP Shipping a test harness with your class in PHP Serialization - storing and reloading objects Abstract classes, Interfaces, PHP and Java Object Oriented programming - a practical design example PHP4 v PHP5 - Object Model Difference Cleaning up redundant objects When should I use OO techniques? PHP - getclass v instanceof Introduction to Object Oriented Programming Sorting objects in PHP Calling base class constructors Accounts in PHP - an OO demo OO PHP demonstration - comparing objects and more This article Object Oriented Model - a summary of changes from PHP4 to PHP5 Cue the music, I'm happy. Build on what you already have with OO Planning a hotel refurb - an example of a Gant chart in PHP Think about your design even if you don't use full UML North, Norther and Northest - PHP 5 Objects Don't repeat code - use loops or functions Should I use structured or object oriented? PHP5 lets you say no PHP v Java Object Oriented Programming in PHP G996 - Newsletter Scripts Oops - I typed ci not vi, and have lost my file ... Changing Images Controlling, supressing, enabling PHP error messages Error Handling in Lua with assert and pcall Grouping rows for a summary report - MySQL and PHP Using the internet to remotely check for power failure at home (PHP) Finding variations on a surname mod_rewrite for newcomers Ajax - going Asyncronous and what it means First class functions in Lua lead to powerful OO facilities Factory method example - Perl Replacing the last comma with an and Script to present commonly used images - PHP Efficient PHP applications - framework and example Error logging to file not browser in PHP Resetting session based tests in PHP This article mysqldump and mysqlrestore Final, Finally and Finalize - three special words in Java .pdf files - upload via PHP, store in MySQL, retrieve C233 - OO in C++ - beyond the basics Variables, Pointers and References - C and C++ When do I use the this keyword in C++? Designing a base class and subclasses, and their extension, in C++ Final examples for 2014 - and a look at our 2015 training course options Object factories in C++, Python, PHP and Perl Extended and Associated objects - what is the difference - C++ example Associated Classes - using objects of one class within another Destructor methods in C++ - a primer C++ - objects that are based on other objects, saving coding and adding robustness C and C++ - preprocess, compile, load, run - what each step is for Private and Public - and things between C++ - putting the language elements together into a program C++ objects - some short, single file demonstrations C++ - a complete example with polymorphism, and how to split it into project files Objects and Inheritance in C++ - an easy start Complete teaching example - C++, inheritance, polymorphism Calling base class constructors What a lot of files! (C++ / Polymorphism demo) C - structs and unions, C++ classes and polymorphism This article C++ - just beyond the basics. More you can do Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Simple polymorphism example - C++ References and Pointers in C++