简体   繁体   中英

JavaScript Design Patterns: Abstract Factory vs Concrete Factory

What is the difference between concrete factories and abstract factories?

PS: I originally asked a question " what is a concrete factory ". Asked my doubt here in a separated question to keep the two discussions separate.

事情是抽象工厂只是抽象类,具体工厂给出抽象类的真实实现

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM