当前位置:网站首页>工厂模式(Swift 实现)
工厂模式(Swift 实现)
2022-07-30 05:43:00 【大头鑫】
Factory Method 工厂模式
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() -> Cake
func 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()
边栏推荐
猜你喜欢

Mycat2.0 build tutorial

21. Kotlin Advanced Learning: Implementing Simple Network Access Encapsulation

【面经】米哈游数据开发面经

Monstache执行Monstache - f配置。toml出错不存在处理器类型和名称(附件)(= parse_exc类型

十二、Kotlin进阶学习:一、Lambda 表达式;二、高阶函数;

Function 函数式接口及应用

Nodejs PM2 monitoring and alarm email (2)

C#下大批量一键空投实现

学生成绩管理系统(C语言版)

MySQL - Function and Constraint Commands
随机推荐
MySQL data types and footprint
《MySQL高级篇》四、索引的存储结构
[MATLAB] Image Processing - Recognition of Traffic Signs
C# WPF中监听窗口大小变化事件
Offensive and defensive world easy_web
Nodejs PM2 monitoring and alarm email (2)
学生管理系统
shardingsphere 分库分表及配置示例
Competition WP in May
[Ten years of network security engineers finishing] - 100 penetration testing tools introduction
TDengineGUI cannot connect to TDengine
在线sql编辑查询工具sql-editor
C#中使用OleDb操作access数据库
SQL Server Installation Tutorial
MySQL - 多表查询与案例详解
C#利用开源NPlot实现K线图(蜡烛图)
MySQL 5.7 安装教程(全步骤、保姆级教程)
二十二、Kotlin进阶学习:简单学习RecyclerView实现列表展示;
C#下大批量一键空投实现
Jackson serialization failure problem - oracle data return type can't find the corresponding Serializer