当前位置:网站首页>工厂模式(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()
边栏推荐
- 十、Kotlin基础学习:1、延迟加载;2、异常处理;3、使用 throw 主动抛出异常;4、自定义异常;
- 【数仓】数据质量
- MySQL index optimization and failure scenarios
- [MATLAB]图像处理——交通标志的识别
- C#下利用开源NPlot绘制股票十字交叉线
- 十四、Kotlin进阶学习:一、内联函数 inline;二、泛型;三、泛型约束;四、子类与子类型;
- Detailed introduction to the usage of Nacos configuration center
- Mycat2.0搭建教程
- "MySQL Advanced Chapter" four, the storage structure of the index
- Flink-流/批/OLAP一体得到Flink引擎
猜你喜欢

十四、Kotlin进阶学习:一、内联函数 inline;二、泛型;三、泛型约束;四、子类与子类型;

Flink CDC implements Postgres to MySQL streaming processing transmission case

SQL Server database generation and execution of SQL scripts

Using PyQt5 to add an interface to YoloV5 (1)

MySQL data types and footprint

SQL Server 数据库之生成与执行 SQL 脚本

vulnhub-XXE ctf security question

sql中 exists的用法
Volatility memory forensics - command shows

【数仓】数据仓库高频面试题题英文版(1)
随机推荐
Function functional interface and application
2022CISCNmisc
C#预定义数据类型简介
Oracle数据库SQL优化详解
MySQL 5.7 安装教程(全步骤、保姆级教程)
[Ten years of network security engineers finishing] - 100 penetration testing tools introduction
Go简单实现协程池
The types of data structures and MySQL index
Online sql editing query tool sql-editor
C#利用开源NPlot实现K线图(蜡烛图)
在线sql编辑查询工具sql-editor
MySQL 5.7 installation tutorial (all steps, nanny tutorials)
MySQL 索引的数据结构及类型
c#下Web3合约空投、转账调用代码
线程的5种状态
uni-app: The use of uni-icons and how to customize icons
MySQL 数据类型及占用空间
【Spark】Spark 高频面试题英语版(1)
[MATLAB] Image Processing - Recognition of Traffic Signs
十九、Kotlin进阶学习:1、管道数据的收和发;2、管道的关闭;3、生产者和消费者;4、管道的缓存区;