Another design pattern today! The second most common (after the singleton) is,
in my opinion factory method. It’s a creational design pattern, that’s
useful when you need to control creation process of the objects a little more
than by a constructor.
For instance you might want to decide what subclass to create at the runtime
rather than while writing the code. Or you don’t care what subclass will be
constructed. Factory method in some more advanced implementations also allows
reusing old objects insead of always creating new instances. The factory
method will give you an object when you request it, but the creation process
is encapsulated. That encapsulation is enforced, and allows an object to be
requested without inextricable coupling to the act of creation.
Detailed description of the design pattern can be found at
I’ll just throw in the code. In my examples, there’s a base class – a Cup
and two subclasses RedCup and BlueCup . The base class has a factory method
that will get you a cup of the color you like.