当前位置:网站首页>工厂模式(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()
边栏推荐
- 网上说的挖矿究竟是什么? 挖矿系统开发详解介绍
- Obtain geographic location and coordinates according to ip address (offline method)
- 【数仓】数据仓库高频面试题题英文版(1)
- uni-app: The use of uni-icons and how to customize icons
- 【调优】一个 Spark 任务某天突然变慢怎么解决
- Common exception analysis of Redis client
- 批量自动归集
- 《MySQL高级篇》四、索引的存储结构
- 十八、Kotlin进阶学习:1、挂起函数执行的顺序;2、使用 async 和 await 异步执行挂起函数;3、协程的调度器;4、父子协程;
- misc-log analysis of CTF
猜你喜欢
mysql is not an internal or external command, nor is it a runnable program or batch file to resolve
Awd summary
使用PyQt5为YoloV5添加界面(一)
JVM Learning (2) Garbage Collector
Detailed introduction to the usage of Nacos configuration center
MySQL 5.7 安装教程(全步骤、保姆级教程)
[Mozhe Academy] Identity Authentication Failure Vulnerability Actual Combat
Flink CDC implements Postgres to MySQL streaming processing transmission case
TDengine cluster construction
protobuf编码及网络通信应用(一)
随机推荐
mysql不是内部或外部命令,也不是可运行的程序或批处理文件解决
Invalid bound statement (not found)出现的原因和解决方法
Bubble sort, selection sort, insertion sort, quick sort
MySQL data types and footprint
C#下大批量一键空投实现
标准输入输出流(System.in,System.out)
十九、Kotlin进阶学习:1、管道数据的收和发;2、管道的关闭;3、生产者和消费者;4、管道的缓存区;
[HCTF 2018]admin
学生成绩管理系统(C语言版)
Mysql 客户端常见异常分析
TDengineGUI cannot connect to TDengine
Reasons and solutions for Invalid bound statement (not found)
《MySQL高级篇》四、索引的存储结构
Student achievement management system (C language version)
C#中对委托的理解和使用
Extraction of BaseDAO
Monstache执行monstache -f config.toml出错No processor type exists with name [attachment] [type=parse_exc
sqli-labs shooting range SQL injection learning Less-1
Common exception analysis of Redis client
使用PyQt5为YoloV5添加界面(一)