工厂设计模式如何在下面的例子中帮助我们?

How does the Factory Design Pattern is help us in following example?

我正在考虑这个例子Factory Design Pattern 假设我有 2 个客户端使用此通知库,在以下情况下,各个客户端的代码将如下所示。

情况一:没有工厂模式

Client 1

SMSNotification notification = new SMSNotification();
notification.notifiyUser();

Client 2

EmailNotification notification = new EmailNotification();
notification.notifiyUser();

案例 2:使用工厂模式

Client 1

Notification notification = notificationFactory.createNotification("SMS");
notification.notifiyUser();

Client 2

Notification notification = notificationFactory.createNotification("Email");
notification.notifiyUser();

所以现在如果假设通知团队在他们的库中添加了一个新的通知系统,并且假设客户 2 想要包含它,那么在情况 1 中我必须更改具体的 class 名称,在情况 2 中我必须将字符串值更改为新值,因此无论如何我都必须进行更改。

工厂设计模式有何帮助?

快速回答

您可以从外部 属性 文件读取“SMS”或“Email”字符串。

然后您可以配置您的工厂而无需重新编译您的项目。


补充信息

我们还使用一种称为关注点分离的设计原则 SoC。可以有多个“关注点”来分离,例如,业务逻辑和数据检索。

其中一个 SoC 正在分离配置和应用程序逻辑。应用它,我们可以配置我们的应用程序的行为,这非常有帮助。

例如,我们可以在测试环境和生产环境中使用相同的应用程序代码 运行,唯一不同的是配置。 在您的示例中,我们可以在测试环境中有一个“Fake-email”工厂 运行,以防止我们向实际客户发送不需要的电子邮件(真实故事)。

您可以拥有一个数据库 table(如果可能的话),其中包含服务的详细信息,例如“短信”、“电子邮件”、“推送”等

然后您可以阅读此 table 并将通知服务的值传递给 notificationFactory.createNotification(ServiceNamereturnedfromtable);

通过这种方式,您不需要重新编译整个项目,而只需维护一个 table 您可以在其中添加/删除/禁用/启用通知服务。