JavaScript Design Patterns: Abstract Factory Vs Concrete Factory
Solution 1:
The thing is abstract factories are just abstract class the concrete factories give the real implementation of the abstract classes
Solution 2:
The difference will be easier to see from the perspective of a client class which makes use of the factory class.
If the client class uses a concrete factory class, then it will be difficult to reuse the client class in another context. We cannot replace the current in-used concrete factory class by another concrete factory class without modifying source code of the client class.
In contrast, if the client uses an abstract factory class (or interface), we can easily reuse the client class with another (concrete) factory class because the source code of the client class does not mention any concrete factory class. For example, consider the code below:
interface AbstractFactory { Product create(); }
class Client {
private AbstractFactory factory;
public Client(AbstractFactory factory) { this.factory = factory; }
public void foo() { /* use this.factory */ }
}
// Now we can reuse the Client class with any concrete factory class
class ConcreteFactory1 implements AbstractFactory { ... }
class ConcreteFactory2 implements AbstractFactory { ... }
Client client1 = new Client(new ConcreteFactory1());
client1.foo();
Client client2 = new Client(new ConcreteFactory2());
client2.foo();
As you see, in any case, source code of the Client
class does not need to be modified, but it still works with different concrete factory class.
Post a Comment for "JavaScript Design Patterns: Abstract Factory Vs Concrete Factory"