Factory design pattern
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 the 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 behavior 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 class. We could have used an Interface instead of an Abstract class, also.
factory design pattern – PHP code example 2
Factory method design pattern is used to create objects of different classes without specifying the exact object to be created but let subclasses decide which class to instantiate. Factory design pattern only defines an Interface ( or a Class that is used as an Interface or a blueprint object ) that is required for this operation. Factory design pattern ( or Factory method design pattern ) is the right way to keep the use of the
new keyword in check, and by that, our web app clean and simple to maintain in future updates. We will be covering and using design patterns like this in future sessions so stay tuned.
Posted on: October 25, 2019
Print article Email article