Factory Mode 工厂模式
Provide the method for creating an instance in the superclass, and allow the subclass to choose the type of the instance.
在父类中提供创建对象的方法,允许子类决定实例化对象的类型。
具备的部分:生产者协议、产品协议,往后就可以根据需要来扩展每一种产品。
具体的生产者比如 MongoCakeCreator
的存在是为了实现与产品相关的核心业务逻辑,而不仅仅是创建 MongoCake
实例。工厂方法将核心业务逻辑从具体产品类中分离出来。
// Creator
protocol CakeCreator {func createCake() -> Cakefunc doSomethingForCake(cake: Cake) -> Cake
}// Product
protocol Cake {func doWork()
}// ConcreteCreator
class MongoCakeCreator: CakeCreator {var cake: MongoCake?func createCake() -> Cake {var cake = MongoCake()doSomethingForCake(cake: cake)return cake}func doSomethingForCake(cake: Cake) -> Cake{cake.doWork()cake.doWork()return cake}}// ConcreteCreator
class ChocolateCakeCreator: CakeCreator {func createCake() -> Cake {var cake = ChocolateCake()doSomethingForCake(cake: cake)return cake}func doSomethingForCake(cake: Cake) -> Cake{cake.doWork()return cake}
}class MongoCake: Cake {func doWork() {print("Add some mongo")}
}class ChocolateCake: Cake {func doWork() {print("Add some chocolate")}
}// If we want to add a type of cake call "PinapleCake", just need to
// make it conform to Cake and add a creator that conform to the CakeCreator for the "PinapleCake"let cakeOne = MongoCakeCreator().createCake()