Article Preview
Buy Now
FEATURE
Design Patterns Part 3
The Factory Pattern
Issue: 22.2 (March/April 2024)
Author: Marc Zeedar
Author Bio: Marc taught himself programming in high school when he bought his first computer but had no money for software. He's had fun learning ever since.
Article Description: No description available.
Article Length (in bytes): 13,959
Starting Page Number: 26
Article Number: 22003
Resource File(s):
project-22003.zip Updated: 2024-02-29 23:35:15
Related Link(s): None
Excerpt of article text...
In my previous articles in this series, I've covered the Iterator and Decorator (Wrapper) Design Patterns. Today we're going to tackle the Factory pattern.
What is a Factory? In short, it's a method that returns a new object. Now you might wonder, like I initially did, why you need a Factory to create a new object. Can't I just write
myObject = new objectKind
to create a new object?Yes, of course you can. But then you've hard-coded the object type into this code. That is coupling your code to that object type. That makes it much more difficult to change the structure of your program because you have to edit more code to make those modifications.
A Factory gets around that because a Factory can make a variety of objects, which helps decouple your external code, and it makes your external code more flexible. Remember, the more generic an object your code works with, the less code you have to modify when your program changes.
A Bad Code Example
It may sound strange, but I learn more from studying bad code than I do from good code. In good code, the work is already done. I can see it and admire it, but I don't know how we got there. With bad code, I can see the problems, and by learning how to fix it, I gain much more practical knowlege.
...End of Excerpt. Please purchase the magazine to read the full article.