当前位置:网站首页>工厂模式(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扩展插件/依赖项简化代码(在最新版本4.0以后,此插件已被弃用,故请选择性学习,以了解为主。)

MySQL 5.7 安装教程(全步骤、保姆级教程)

十七、Kotlin进阶学习:1、守护线程;2、线程和协程之间的效率对比;3、取消协程;
Bypassing the file upload vulnerability

Mycat2.0搭建教程

Using PyQt5 to add an interface to YoloV5 (1)

MySQL 5.7 installation tutorial (all steps, nanny tutorials)

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

Function functional interface and application

vulnhub-XXE ctf security question
随机推荐
【数仓】数据质量
网上说的挖矿究竟是什么? 挖矿系统开发详解介绍
uni-app: The use of uni-icons and how to customize icons
二十二、Kotlin进阶学习:简单学习RecyclerView实现列表展示;
MySQL 索引优化及失效场景
十七、Kotlin进阶学习:1、守护线程;2、线程和协程之间的效率对比;3、取消协程;
C#中使用OleDb操作access数据库
【SQL】SQL 高频面试题英语版(1)
Jackson 序列化失败问题-oracle数据返回类型找不到对应的Serializer
Kotlin协程的简单用法:1、GlobalScope(不建议使用);2、lifecycleScope、viewModelScope(建议使用);
SQL Server database generation and execution of SQL scripts
标准输入输出流(System.in,System.out)
c#下Web3合约空投、转账调用代码
Briefly describe SSRF
Servlet basic principles and application of common API methods
[HCTF 2018]admin
Jdbc & Mysql timeout analysis
uni-app: about custom components, easycom specs, uni_modules, etc.
Using custom annotations, statistical method execution time
Competition WP in May