It allows a calling component to obtain a family or group of related objects without needing to know which classes were used to create them.
每一层的创建都是工厂,并且客户端和中间层是不知道具体零件的类型的。
client:
let car =
Car(carType: Cars.SPORTS);
car.printDetails();
design pattern:
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;
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() {
println("Car type:
\(carType.rawValue)");
println("Seats:
\(floor.seats)");
println("Engine:
\(floor.enginePosition.rawValue)");
println("Suspension:
\(suspension.suspensionType.rawValue)");
println("Drive:
\(drive.driveType.rawValue)");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CarFactory {
required
init() {
// do nothing
}
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 factoryType:CarFactory.Type;
switch (car) {
case .COMPACT:
factoryType =
CompactCarFactory.self;
case .SPORTS:
factoryType =
SportsCarFactory.self;
case .SUV:
factoryType =
SUVCarFactory.self;
}
var factory = factoryType.sharedInstance;
if (factory == nil) {
factory = factoryType();
}
return factory;
}
class var sharedInstance:CarFactory? {
get {
return nil;
}
}
}
class CompactCarFactory :
CarFactory {
override func createFloorplan() ->
Floorplan {
return
StandardFloorplan();
}
override func createSuspension() ->
Suspension {
return
RoadSuspension.getInstance();
}
override func createDrivetrain() ->
Drivetrain {
return
FrontWheelDrive();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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
}