Design Patterns: Abstract Factory vs Factory C#
The main difference between a “factory method” and an “abstract factory” is that the factory method is a method, and an abstract factory is an object.
The Factory Method:
The factory method is just a method, it can be overridden in a subclass. In other words, the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.
An object is calling its own factory method here. Therefore the only thing that could change the return value would be a subclass.
Factory Code Example:
class A {
public void doSomething() {
Foo f = makeFoo();
f.whatever();
}
protected Foo makeFoo() {
return new RegularFoo();
}
}
class B : A {
protected Foo makeFoo() {
//subclass is overriding the factory method
//to return something different
return new SpecialFoo();
}
}
The Abstract Factory Method:
Abstract factory is an object that has multiple factory methods on it. In other words, the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition.
There is an object A, who wants to make a Foo object. Instead of making the Foo object itself (e.g., with a factory method), it’s going to get a different object (the abstract factory) to create the Foo object.
Abstract Factory Code Example:
class A {
private Factory factory;
public A(Factory factory) {
this.factory = factory;
}
public void doSomething() {
//The concrete class of "f" depends on the concrete class
//of the factory passed into the constructor. If you provide a
//different factory, you get a different Foo object.
Foo f = factory.makeFoo();
f.whatever();
}
}
interface Factory {
Foo makeFoo();
Bar makeBar();
Abc makeAmbiguousYetCommonlyUsedFakeClassName();
}
//need to make concrete factories that implement the "Factory" interface here
Conclusion
I hope you found this article useful. Don’t forget to clap and follow me for more great articles!
Happy Coding!