扫码阅读
手机扫码阅读

3种工厂模式的比较

147 2024-10-03

我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。

查看原文:3种工厂模式的比较
文章来源:
麦哲思科技任甲林
扫码关注公众号
Design Patterns Summary

Design Patterns Summary

The article discusses three common design patterns used to create objects without exposing the creation logic to the client and thereby providing a way to refer to newly created objects using a common interface.

Simple Factory

In the Simple Factory pattern, a single concrete factory class uses conditional statements to create various products. The product creation logic is centralized within one factory class. Clients can create different products by passing different parameters to the factory. However, adding new products requires alteration of the factory class and addition of new product classes, which violates the Open-Closed Principle (OCP).

Factory Method

The Factory Method pattern involves a hierarchy where each factory creates a single product. All concrete factories inherit from one abstract factory class. The client first creates a factory specific to the product they wish to create, and then the factory creates the actual product. The product creation logic is distributed across each concrete factory class. Clients depend only on the abstract factory and product interfaces, not on any concrete implementations. Adding new products is achieved by adding new factory and product classes, which conforms to the OCP.

Abstract Factory

The Abstract Factory pattern allows for the creation of a family of related or dependent products by a single concrete factory. Each product family is a combination of different series of products, and the logic for creating products is contained within each concrete factory class. All concrete factories inherit from the same abstract factory. Clients create factories specific to the product family, and the creation of concrete products is hidden from the client. While adding new product families conforms to the OCP by requiring new concrete factory classes, adding new individual products within a family violates the OCP as it necessitates changes to concrete factory classes and the addition of new product classes. The use of the abstract factory pattern is not recommended if there's no need to cater for the creation of multiple series of products; in such cases, a simple static factory would suffice.

All three patterns discussed help decouple the client from the actual products, as clients are not concerned with the specific methods of product production.

想要了解更多内容?

查看原文:3种工厂模式的比较
文章来源:
麦哲思科技任甲林
扫码关注公众号

麦哲思科技(北京)有限公司总经理 敏捷性能合弄模型评估师 认证的Scrum Master 认证的大规模敏捷顾问SPC CMMI高成熟度主任评估师 COSMIC MPC,IAC 成员,中国分部主席

425 篇文章
浏览 135.5K
加入社区微信群
与行业大咖零距离交流学习
软件研发质量管理体系建设 白皮书上线