Creating form element objects through the form element factory is a fairly straightforward process. Object instantiation is handled internally behind the interface of the class, so the code looks compact and readable. Let's start factoring some form element objects, to clarify the usage of the factory:
The above snippet simply creates several form objects. Note that object instantiation is performed behind the scenes, each time the "createElement()" method is invoked with the proper parameters. Since this method is static, it's possible to call it outside the class context by using the (::) resolution scope operator.
If you think that the above examples are not complete, here is code to instantiate the rest of form element objects:
Finally, let's implement a basic loop, for roughly rendering some objects:
// make array with form element objects
After executing the above snippet, what you get is a crude visual presentation of the form elements included in the array. Of course, a more polished look is highly desired, but for the moment, let's settle for the elements' rendering process of this example.
As you can see, the defined "formElementFactory" class is doing its job quite well, despite its simplicity. Definitely, we've stepped forward to use the Factory Pattern within the form creation process, while the overall code has been maintained at a simple level.
Notice the evident separation between object instantiation and the rest of client code. There are no "new" constructs that indicate where the objects are created. The whole process is handled by the internals of the "formElementFactory" class.
There are still many aspects that need to be improved within the application, but you should remember that this is merely the beginning. The logic of the factory class must be modified, in order to get a higher level of abstraction to instantiate form objects, as well as get more control over visual presentation.
For many of these features to work, you'll have to wait for the next part of the series. However, these are just a few ideas to get you started using the Factory pattern in real applications.
Through this article, I've exposed the basics for implementing the Factory pattern in a real situation: building object-oriented forms. To fit this objective, a form element factory class has been defined, by showing that object instantiation can be completely decoupled from the client code, so a greater level of abstraction for rendering web-based forms is obtained within a program.
Over the next part of the series, I'll add some features to the factory class, in order to encapsulate element rendering code within its structure. Meanwhile, play with the code and study its functionality. See you in the next part!
blog comments powered by Disqus