创建者模式-抽象工厂模式(The Abstract Factory Pattern)

本文大部分内容翻译至《Pro Design Pattern In Swift》By Adam Freeman,一些地方做了些许修改,并将代码升级到了Swift2.0,翻译不当之处望多包涵。

抽象工厂模式(The Abstract Factory Pattern)

抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。客户端程序不需要知道(或关心)它从这些内部的工厂方法中获得对象的具体类型,因为客户端程序仅使用这些对象的通用接口。抽象工厂模式将一组对象的实现细节与他们的一般使用分离开来。


示例工程

OS X Command Line Tool 工程:

Floorplans.swift

protocol Floorplan {
    var seats:Int { get }
    var enginePosition:EngineOption { get }
}

enum EngineOption : String {
    case FRONT = "Front"
    case MID = "Mid"
}

class ShortFloorplan: Floorplan {
    var seats = 2
    var enginePosition = EngineOption.MID
}

class StandardFloorplan: Floorplan {
    var seats = 4
    var enginePosition = EngineOption.FRONT
}

class LongFloorplan: Floorplan {
    var seats = 8
    var enginePosition = EngineOption.FRONT
}

定义了一个协议Floorplan 代表车的构建,枚举EngineOption代表引擎的位置等。接着我们看另一个相关Suspension(汽车悬架):

Suspension.swift

protocol Suspension {
    var suspensionType:SuspensionOption { get }
}

enum SuspensionOption : String {
    case STANDARD = "Standard"
    case SPORTS = "Firm"
    case SOFT = "Soft"
}

class RoadSuspension : Suspension {
    var suspensionType = SuspensionOption.STANDARD
}

class OffRoadSuspension : Suspension {
    var suspensionType = SuspensionOption.SOFT
}

class RaceSuspension : Suspension {
    var suspensionType = SuspensionOption.SPORTS
}

接下来是Drivetrains(汽车动力传动系统):

Drivetrains.swift

protocol Drivetrain {
    var driveType:DriveOption { get }
}

enum DriveOption : String {
    case FRONT = "Front"
        case REAR = "Rear"
        case ALL = "4WD"
}

class FrontWheelDrive : Drivetrain {
    var driveType = DriveOption.FRONT
}

class RearWheelDrive : Drivetrain {
    var driveType = DriveOption.REAR
}

class AllWheelDrive : Drivetrain {
    var driveType = DriveOption.ALL
}

最后我们创建CarsParts.swift文件:

CarsParts.swift

enum Cars: String {
    case COMPACT = "VW Golf"
    case SPORTS = "Porsche Boxter"
    case SUV = "Cadillac Escalade"
}

struct Car {
    var carType:Cars
    var floor:Floorplan
    var suspension:Suspension
    var drive:Drivetrain
    
    func printDetails() {
        print("Car type: \(carType.rawValue)")
        print("Seats: \(floor.seats)")
        print("Engine: \(floor.enginePosition.rawValue)")
        print("Suspension: \(suspension.suspensionType.rawValue)")
        print("Drive: \(drive.driveType.rawValue)")
    }
}

理解抽象工厂模式解决的问题

工厂方法模式允许请求组件不需要知道各种细节而获得一个实现类的实例, 而抽象工厂解决的问题有点类似但是一组并非实现同一个协议或者继承相同基类的相关的对象。


创建者模式-抽象工厂模式(The Abstract Factory Pattern)_第1张图片

我们修改main.swift

main.swift

var car = Car(carType: Cars.SPORTS,
    floor: ShortFloorplan(),
    suspension: RaceSuspension(),
    drive: RearWheelDrive())

car.printDetails()

运行程序,得到下面输出:

Car type: Porsche Boxter
Seats: 2
Engine: Mid
Suspension: Firm
Drive: Rear

理解抽象工厂模式

抽象工厂模式和工厂方法模式都是为了解决同一个问题,但是抽象工厂模式是用在创建一组对象,并且这些对象并没有实现同一个协议或者继承相同的基类。在示例中,构建一个Car结构体需要三个对象,并且每一个对象实现的不同的协议:Floorplan, Suspension, Drivetrain 。

抽象工厂模式用合并的方式来解决散乱的对象选择逻辑问题,用只向请求组件提供协议来解决依赖问题。


创建者模式-抽象工厂模式(The Abstract Factory Pattern)_第2张图片
  1. 提供一个抽象工厂类,定义了一个返回一个协议实例或者基类实例的方法。
  2. 抽象工厂方法检查调用者的请求并选择一个具体工厂类,这个工厂类就是实现了工厂方法模式的类。具体工厂类的实例就被创建了并返回给了调用者。
  3. 调用者调用具体工厂类的的工厂方法。
  4. 实现类被初始化并提供给调用者。

实现抽象工厂模式

  • 创建抽象工厂

Abstract.swift

class CarFactory {
    func createFloorplan() -> Floorplan {
        fatalError("Not implemented")
    }
    
    func createSuspension() -> Suspension {
        fatalError("Not implemented")
    }
    
    func createDrivetrain() -> Drivetrain {
        fatalError("Not implemented")
    }
}
  • 创建具体工厂

Concrete.swift

class CompactCarFactory : CarFactory {
    override func createFloorplan() -> Floorplan {
        return StandardFloorplan()
    }
    override func createSuspension() -> Suspension {
        return RoadSuspension()
    }
    override func createDrivetrain() -> Drivetrain {
    return FrontWheelDrive()
    }
}

class SportsCarFactory : CarFactory {
    override func createFloorplan() -> Floorplan {
        return ShortFloorplan()
        }
    override func createSuspension() -> Suspension {
        return RaceSuspension()
        }
    override func createDrivetrain() -> Drivetrain {
        return RearWheelDrive()
        }
}
class SUVCarFactory : CarFactory {
    override func createFloorplan() -> Floorplan {
        return LongFloorplan()
        }
    override func createSuspension() -> Suspension {
        return OffRoadSuspension()
        }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
        }
}
  • 完成抽象工厂

Abstract.swift

class CarFactory {
    func createFloorplan() -> Floorplan {
        fatalError("Not implemented")
    }
    
    func createSuspension() -> Suspension {
        fatalError("Not implemented")
    }
    
    func createDrivetrain() -> Drivetrain {
        fatalError("Not implemented")
    }
    
    final class func getFactory(car:Cars) -> CarFactory? {
        var factory:CarFactory?
        switch (car) {
        case .COMPACT:
            factory = CompactCarFactory()
        case .SPORTS:
            factory = SportsCarFactory()
        case .SUV:
            factory = SUVCarFactory()
        }
        return factory
    }
}
  • 消费抽象工厂模式

最后一步就是更新Car对象,让它从抽象工厂中获得产品对象。

main.swift

let factory = CarFactory.getFactory(Cars.SPORTS)
if (factory != nil) {
    let car = Car(carType: Cars.SPORTS,
    floor: factory!.createFloorplan(),
    suspension: factory!.createSuspension(),
    drive: factory!.createDrivetrain())
    car.printDetails()
}

运行程序,得到和上面一样的结果:

Car type: Porsche Boxter
Seats: 2
Engine: Mid
Suspension: Firm
Drive: Rear

我们可以看出main.swift和独立的产品类之间没有了依赖。我们可以直接改变具体工厂类而不修改main.swift。

Concrete.swift

...
class SportsCarFactory : CarFactory {
    override func createFloorplan() -> Floorplan {
        return ShortFloorplan()
        }
    override func createSuspension() -> Suspension {
        return RaceSuspension()
        }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
        }
}
...

再次运行程序:

Car type: Porsche Boxter
Seats: 2
Engine: Mid
Suspension: Firm
Drive: 4WD

抽象工厂模式的变形

  • 隐藏抽象工厂类

第一个最普通的变形就是将抽象工厂模式的实现隐藏结构体或者类中。在本例中显然就是Car类。

CarParts.swift

...
struct Car {
    var carType:Cars
    var floor:Floorplan
    var suspension:Suspension
    var drive:Drivetrain
    
    init(carType:Cars) {
        let concreteFactory = CarFactory.getFactory(carType)
        self.floor = concreteFactory!.createFloorplan()
        self.suspension = concreteFactory!.createSuspension()
        self.drive = concreteFactory!.createDrivetrain()
        self.carType = carType
    }
    
    func printDetails() {
        print("Car type: \(carType.rawValue)")
        print("Seats: \(floor.seats)")
        print("Engine: \(floor.enginePosition.rawValue)")
        print("Suspension: \(suspension.suspensionType.rawValue)")
        print("Drive: \(drive.driveType.rawValue)")
    }
}

这样一来,main.swift就变得更简单了:

main.swift

let car = Car(carType: Cars.SPORTS)
car.printDetails()
  • 具体工厂类实现单例模式

另一个很普遍的变形就是具体工厂类实现单例模式。

class CarFactory {
    
    func createFloorplan() -> Floorplan {
        fatalError("Not implemented")
    }
    
    func createSuspension() -> Suspension {
        fatalError("Not implemented")
    }
    
    func createDrivetrain() -> Drivetrain {
        fatalError("Not implemented")
    }
    
    final class func getFactory(car:Cars) -> CarFactory? {
        var factory:CarFactory
        switch (car) {
        case .COMPACT:
            factory = CompactCarFactory.sharedInstance
        case .SPORTS:
            factory = SportsCarFactory.sharedInstance
        case .SUV:
            factory = SUVCarFactory.sharedInstance
        }
        return factory
    }
}

接下来修改:

Concrete.swift

class CompactCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = CompactCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return StandardFloorplan()
    }
    
    override func createSuspension() -> Suspension {
        return RoadSuspension()
    }
    
    override func createDrivetrain() -> Drivetrain {
        return FrontWheelDrive()
    }
}

class SportsCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = SportsCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return ShortFloorplan()
    }
    override func createSuspension() -> Suspension {
        return RaceSuspension()
    }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
    }
}

class SUVCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = SUVCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return LongFloorplan()
    }
    override func createSuspension() -> Suspension {
        return OffRoadSuspension()
    }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
    }
}
  • 为实现类应用原型模式

最重要的是为实现类去应用原型模式而非具体工厂类。

Suspersion.swift

import Foundation

protocol Suspension {
    var suspensionType:SuspensionOption { get }
}

enum SuspensionOption : String {
    case STANDARD = "Standard"
    case SPORTS = "Firm"
    case SOFT = "Soft"
}
***

class RoadSuspension :NSObject, NSCopying,Suspension {

    var suspensionType = SuspensionOption.STANDARD
        
    static let sharedInstance = RoadSuspension()
        
    func copyWithZone(zone: NSZone) -> AnyObject {
        return RoadSuspension()
            
    }
        
    class func getInstance() -> Suspension {
        return sharedInstance.copy() as! Suspension
        
    }
    
}

class OffRoadSuspension :NSObject, NSCopying, Suspension {
    
    var suspensionType = SuspensionOption.SOFT
    
    static let sharedInstance = OffRoadSuspension()
    
    func copyWithZone(zone: NSZone) -> AnyObject {
        return OffRoadSuspension()
        
    }
    
    class func getInstance() -> Suspension {
        return sharedInstance.copy() as! Suspension
        
    }
}

class RaceSuspension :NSObject, NSCopying,  Suspension {
    
    var suspensionType = SuspensionOption.SPORTS
    
    static let sharedInstance = RaceSuspension()
    
    func copyWithZone(zone: NSZone) -> AnyObject {
        return RaceSuspension()
        
    }
    
    class func getInstance() -> Suspension {
        return sharedInstance.copy() as! Suspension
        
    }
}

接下来修改:

Concrete.swift

class CompactCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = CompactCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return StandardFloorplan()
    }
    
    override func createSuspension() -> Suspension {
        return RoadSuspension.getInstance()
    }
    
    override func createDrivetrain() -> Drivetrain {
        return FrontWheelDrive()
    }
}

class SportsCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = SportsCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return ShortFloorplan()
    }
    override func createSuspension() -> Suspension {
        return RaceSuspension.getInstance()
    }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
    }
}

class SUVCarFactory : CarFactory {
    
    private override init(){}
    
    static let sharedInstance = SUVCarFactory()
    
    override func createFloorplan() -> Floorplan {
        return LongFloorplan()
    }
    override func createSuspension() -> Suspension {
        return OffRoadSuspension.getInstance()
    }
    override func createDrivetrain() -> Drivetrain {
        return AllWheelDrive()
    }
}

你可能感兴趣的