Software Engineering Asked on October 29, 2021
I always had problems in grasping the full benefits/motif behind using the Factory design pattern (for this post, I will stick to Factory Method pattern
, specifically). True, there are (really) lots of posts over the internet on the topic. But I always had a hard time summarizing the pattern to the problem it comes to solve and how does it solve it.
After one more try researching the internet on the topic, reading posts and watching videos, I think I finally see what does it accomplish (particularly the 3rd bullet below), and that without it, I can’t get rid of the problem it comes to solve (assuming I know no other design patterns).
Here’s how I see it:
The problem:
Pseudo-code illustration:
/*-------------------- client ----------------------------*/
var p1 = new P1Factory.CreateProduct(...);
//new requirement, 2 weeks later
var p2 = new P2Factory.CreateProduct(...);
//2 weeks later
var p3 = new P3Factory.CreateProduct(...);
/*--------------------------------------------------------*/
/*
factory construct - not the ultimate solution, a starting point,
but not the pattern itself, since it still leaves us with (part of)
the problem we wanted to solve
*/
createProduct(enum type)
{
switch(type)
{
case type.P1:
return new P1();
case type.P2:
return new P2();
}
}
//factory method pattern:
interface IProduct
{
doWork();
}
abstract class Factory
{
IProduct CreateProduct(string[] settings);
}
class P1Factory : Factory
{
public IProduct CreateProduct(...)
{
return new P1();
}
}
public class P1 : IProduct
{
public void doWork() { }
}
So adding a new P4 type only requires extending the code base by adding a new class that implements both the interface and the abstract factory.
Is anything I wrote above wrong ? Am I still missing important points in understanding the motifs behind the pattern?
Is anything I wrote above wrong ? Am I still missing important points in understanding the motifs behind the pattern?
No, what you wrote seems pretty reasonable.
There are two big things I think might help:
Answered by Telastyn on October 29, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP