当前位置:网站首页>工厂模式(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()
边栏推荐
- 线程的5种状态
- oracle行转列、列转行总结
- Volatility memory forensics - command shows
- 在线sql编辑查询工具sql-editor
- Twenty-two, Kotlin advanced learning: simply learn RecyclerView to achieve list display;
- MySQL achievement method 】 【 5 words, single table SQL queries
- 【SQL】first_value 应用场景 - 首单 or 复购
- Invalid bound statement (not found)出现的原因和解决方法
- GraphQL (1) Basic introduction and application examples
- [Getting C language from zero basis - navigation summary]
猜你喜欢

正则表达式语法详解及实用实例

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

MySQL achievement method 】 【 5 words, single table SQL queries

Mycat2.0搭建教程

protobuf编码及网络通信应用(一)

十九、Kotlin进阶学习:1、管道数据的收和发;2、管道的关闭;3、生产者和消费者;4、管道的缓存区;

在线sql编辑查询工具sql-editor

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

Competition WP in May
随机推荐
oracle行转列、列转行总结
批量自动归集
MySQL data types and footprint
Jackson 序列化失败问题-oracle数据返回类型找不到对应的Serializer
Jdbc & Mysql timeout analysis
C#中对委托的理解和使用
sqli-labs less3/4 Targeting Notes
C# WPF中监听窗口大小变化事件
sqli-labs shooting range SQL injection learning Less-1
【SQL】first_value 应用场景 - 首单 or 复购
Student achievement management system (C language version)
Shardingsphere depots table and configuration example
uni-app: The use of uni-icons and how to customize icons
JVM学习(二) 垃圾收集器
Detailed explanation of ClickHouse query statement
mysql不是内部或外部命令,也不是可运行的程序或批处理文件解决
nodejs PM2监控及报警邮件发送(二)
Function functional interface and application
FastAPI Quick Start
The first WebAssembly program