3种工厂模式的比较
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
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.
想要了解更多内容?
麦哲思科技(北京)有限公司总经理 敏捷性能合弄模型评估师 认证的Scrum Master 认证的大规模敏捷顾问SPC CMMI高成熟度主任评估师 COSMIC MPC,IAC 成员,中国分部主席
水生
2007年的夏天我去厦门售前,早晨到酒店的餐厅吃饭,刚进餐厅,见一老一少两个穿黄色僧袍的和尚坐在里面吃饭,老和尚慈眉善目,看到我,像我微笑致意,我也点头还礼,我一直认为自己是很有佛缘的人,所以心里想,大概老和尚看我面善,所以和我打招呼吧,自我感觉甚好。在自助取餐的过程中,老和尚频频向我致意。
早餐吃完,经过两位的位置时,老和尚招手叫住了我,说要聊聊,我没有拒绝。坐下后,老和尚说是到福建什么一个出名的名寺开什么法会,看我有缘,和我聊聊,还送我一个开光的佛像,给了我名片,