抽象工厂模式:
YZFactory.swift
import UIKit
public enum FactoryType {
case Tech,Test,Production
}
class YZFactory {
var factoryName = ""
var myType = FactoryType.Production
static func createFactory(_ type: FactoryType) -> YZFactory {
let factory: YZFactory
switch type {
case .Tech:
factory = Technology()
case .Test:
factory = Testors()
default:
factory = Productions()
}
factory.myType = type
return factory
}
func createBreakfast() -> ProductType {
return YZProduct().createProduct()
}
}
class Technology: YZFactory {
override func createBreakfast() -> ProductType {
return DeveloperP().createProduct()
}
}
class Testors: YZFactory {
override func createBreakfast() -> ProductType {
return TestorP().createProduct()
}
}
class Productions: YZFactory {
override func createBreakfast() -> ProductType {
return ProductP().createProduct()
}
}
YZProduct.swift
import UIKit
public enum ProductType {
case Develop,Test,Product
func getDescription() -> String {
switch self {
case .Develop:
return "开发"
case .Test:
return "测试"
default:
return "产品"
}
}
}
class YZProduct {
func createProduct() -> ProductType {
return ProductType.Develop
}
}
class DeveloperP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Develop
}
}
class TestorP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Test
}
}
class ProductP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Product
}
}
调用:
print(YZFactory.createFactory(.Tech).createBreakfast().getDescription())
print(YZFactory.createFactory(.Test).createBreakfast().getDescription())
print(YZFactory.createFactory(.Production).createBreakfast().getDescription())
开发
测试
产品
网友评论