Phabstractic: Abstract Factory Pattern

asherwunk/phabstractic implements an Abstract Factory pattern. To quote Wikipedia:

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn’t know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.[2]

Abstract Factories

The abstract factory class in the link creates other abstract factories. This is much like the Enumeration data type which creates constants/enumerators with specific arguments. Each Abstract Factory is a throw-away object that you can use to create code dynamically for a given factory. The idea is that you edit or work with the object, setting methods, setting constants, etc. and then ‘bake’ the object so that a new AbstractFactory is defined.

Every Abstract Factory has a name, namespace, constants, and methods. The factory name is a string and will be prefixed with “Abstract” in the class name. The namespace is simply where we can find this. Constants are stored in an array (so they can have a key) and methods are stored in a unique set:

Code generation has changed since version 2.  In version 2 the code generating function had it’s own scoped options to contend with.  The object’s main options were re-mapped onto the functions options.  The function in version 3 now uses the objects options instead of its own.  The code for the code generation lays itself out as such:

As you can see all the constants are pushed to uppercase. Each method is prefixed with ‘make’. The thing to note is that this creates an abstract class. You inherit this class and fill in the details for each method. This just lays out the skeleton for you to build off of. You can also use a static method to skip the throw-away object entirely:

This calls the constructor and fills the $factory variable with the throw-away object, which is then, well, thrown away.

(View on github)

This is part of the Phabstractic Library.

If you appreciate my programming please help support me through my Patreon.

photo credit: CTRL via photopin (license)


I'm just a wunk, trying to enjoy life. I am a cofounder of http// and I like computers, code, creativity, and friends.

You may also like...

Leave a Reply

%d bloggers like this: