Factory design pattern
In object oriented programming, the Factory design pattern
is a creational pattern that uses different methods to deal with the problem of creating objects without having to specify the exact class of the object, each time this object needs to be created ( the infamous new
keyword ). This can be done by creating new objects by defining and calling a static method that belongs to the special Factory class. This functionality can also be wrapped up in some type of an interface, and implemented by child classes, or implemented in a base class and optionally overridden by derived classes, rather than by calling a constructor.
factory design pattern - php code example 1
Factory design pattern enables us to redesign code only once in our main Factory method class, rather than changing different instances of Animal object. Also everything that we need for creating an object is wrapped up in this Factory class, so maintaining this code is very clean and easy. However, using the factory design pattern just to be smart is not always needed as such. For simple web apps this can be added complexity which is not necessary ( If you have a blog webpage with two objects - user and article, it really is not a big mistake not to use Factory design pattern ), but if you are creating larger and more complex projects with multiple active classes which can go by the thousands, you will definitely use the Factory pattern and Factory method principle in your code to make it clean and maintainable. Avoiding practices like this in big projects, will give you a big headache in the future as your project grows. You will even maybe find yourself in a position to rewrite the whole app with the Factory design pattern ( and other design patterns as such ) finally implemented. We can additionally control the behaviour of the main Factory class with abstract classes or interfaces ( see AbstractFactoryMethod
class example below ). We can see how our code becomes cleaner now. Abstract class behaves as a blueprint for our AnimalFactory
factory design pattern - php code example 2
Factory design pattern is the right way to keep the use of the
keyword in check, and by that, our web app clean and simple to maintain.