JavaScript设计模式:抽象工厂与混凝土工厂 [英] JavaScript Design Patterns: Abstract Factory vs Concrete Factory

查看:60
本文介绍了JavaScript设计模式:抽象工厂与混凝土工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

混凝土工厂和抽象工厂有什么区别?

What is the difference between concrete factories and abstract factories?

PS:我最初问一个问题"什么是混凝土工厂".在一个单独的问题中问了我的疑问,以使两个讨论分开.

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();

如您所见,在任何情况下,都无需修改 Client 类的源代码,但仍可以与其他具体的工厂类一起使用.

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.

这篇关于JavaScript设计模式:抽象工厂与混凝土工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆