Factory Method: Problem
Example: a logistics management application
示例:物流管理应用程序
– First version: handling transportation by trucks, with a Truck class
– Later: new requests to incorporate sea logistics, and more
– 第一个版本:处理卡车运输,卡车类别 – 后来:纳入海运物流的新请求,等等......
Factory Method: Solution
Replace direct object construction calls (using the new operator) with calls to a special factory method
将直接对象构造调用(使用 new 运算符)替换为对特殊工厂的方法
The client code does not see a difference between the actual products returned by various subclasses
客户端代码看不到各个子类返回的实际产品之间的差异
Abstract Factory: Problem
Example: a furniture shop simulator
示例:家具店模拟器
– A family of related products: Chair + Sofa + CoffeeTable
– Variants of this family: ArtDeco, Victorian, Modern
一系列相关产品:椅子 + 沙发 + 咖啡桌– 该系列的变体:装饰艺术、维多利亚时代、现代
Abstract Factory: Solution
• Firstly, explicitly declare interfaces for each distinct product of the product family, and then make all variants follow the interfaces
首先,为 product 系列的每个不同产品显式声明接口,然后将所有变体实现接口
• Secondly, declare the Abstract Factory: an interface with a list of creation methods for all products, and the methods return abstract product types represented by the interfaces
其次,声明 Abstract Factory:一个接口,其中包含所有产品的创建方法列表,这些方法返回由接口表示的抽象产品类型
• Thirdly, create a separate factory class for each variant
第三,为每个变体创建一个单独的 factory 类
• Finally, the client creates a concrete factory object at the initialization stage
最后,客户端在初始化阶段创建一个具体的工厂对象