Search code examples
phpoopfactory-pattern

understanding Factory method pattern


I am reading factory method pattern as I have some issues related to it but I am unable to understand it from core. As per definition stated here

The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.

I can understand the concept of duplication of significant code, but I am unable to understand the other concepts like it states

It may require information not accessible to the composing object

How a class can contain the infomation which ic not accessible by composing object. As for as I understand it may be any private datamember of the class. But if any thing is private then how object creation process needs that information? Similarly other two point

It may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.

Can any body please here describe these precisely and show my some code stuff so that I can understand the concept


Solution

  • The idea of factory pattern is to create load classes and create new objects dynamically. Quite often it is done as a static class (such as here, in the official PHP documentation), but some frameworks use factory pattern as a way of loading objects within MVC objects, for example when you want to load some data in view through a model.

    The idea of factory pattern is efficiency and resource management. It loads a file only when it's not been loaded yet and returns the newly created object.

    (Note that the example in PHP documentation is not ideal, it would be better to check if the class has been defined and if not, then attempt to include the file instead of using include_once())