[fpc-pascal] Implementing Factory Method with Pascal

Graeme Geldenhuys mailinglists at geldenhuys.co.uk
Sat Nov 28 10:32:05 CET 2015

Hi Marcos,

On 2015-11-27 23:48, Marcos Douglas wrote:
> Why do you have a factory to create different types of animals
> (classes)? Doesn't make sense.

Maybe in Luciano's simple example a factory is not the best use case,
but the Simple Factory design pattern can be very useful in other cases.

eg: tiOPF uses the Simple Factory extensively in many areas. eg:
encryption. tiOPF defines a base class with abstract methods for using
encryption. We then have various descendant classes that implement
different encryption. Each of the descendants register themselves with
the factory (tiOPF likes to use the uses clause and Initialization
section for this). In your own code you then request an encryption type
and get a instance object back. You use that instance via the API
(interface) defined by the abstract methods.

> Objects should be immutable at first place, only if you have a good
> reason for don't use immutability. So, if they should be immutable,

This has nothing to do with Luciano's problem.

> Another tip: use interfaces, not inheritance. Inheritance is evil.

Indeed, Interfaces might be a more elegant solution to Luciano's problem
- for what he wants to achieve. Inheritance is NOT evil. It's not that
black and white. Both Interfaces and Inheritance have their pros and
cons - you just need to study your problem and then decide which is the
better fit.

What you described is the Simple Factory design pattern. I suggest you
also study the Factory Method design pattern, to see the difference and
where you can use them.

Two [I have many more suggestions too] Design Pattern books I highly
recommend are:

  * Design Patterns - Elements Of Reusable Object Oriented Software.
    Also known as the GoF (Gang of Four) book.

  * Head First - Design Patterns
    This one has a very different writing style, but I found this fun
    take on design patterns works very well.

  - Graeme -

fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal

My public PGP key:  http://tinyurl.com/graeme-pgp

More information about the fpc-pascal mailing list