当前位置:网站首页>工厂模式(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()
边栏推荐
- 在不同的服务器上基于docker部署redis主从同步
- Invalid bound statement (not found)出现的原因和解决方法
- 【SQL】SQL 高频面试题英语版(1)
- MySQL - Multi-table query and case detailed explanation
- 十四、Kotlin进阶学习:一、内联函数 inline;二、泛型;三、泛型约束;四、子类与子类型;
- GraphQL(一)基础介绍及应用示例
- 史上超强最常用SQL语句大全
- Oracle数据库SQL优化详解
- vulnhub-XXE ctf security question
- 【MySQL功法】第5话 · SQL单表查询
猜你喜欢
Volatility memory forensics - command shows
![[Mozhe Academy] Identity Authentication Failure Vulnerability Actual Combat](/img/c3/4a4e23a97e4650a17ff5cfc5233043.png)
[Mozhe Academy] Identity Authentication Failure Vulnerability Actual Combat

Arrays工具类的使用

Online sql editing query tool sql-editor

MySQL 数据类型及占用空间

Jdbc & Mysql timeout分析

Offensive and defensive world easy_web

MySQL开窗函数

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

MySQL - Function and Constraint Commands
随机推荐
mysql不是内部或外部命令,也不是可运行的程序或批处理文件解决
Function functional interface and application
网上说的挖矿究竟是什么? 挖矿系统开发详解介绍
Trust anchor for certification path not found. Exception solution.
Competition WP in May
MySQL 数据类型及占用空间
在线sql编辑查询工具sql-editor
Online sql editing query tool sql-editor
【面经】米哈游数据开发面经
Function 函数式接口及应用
FastAPI 快速入门
MySQL - 函数及约束命令
ClickHouse查询语句详解
C#中default关键字用法简介
批量自动归集
sql concat() function
十三、Kotlin进阶学习:内联函数let、also、with、run、apply的用法。
Volatility memory forensics - command shows
TDengineGUI无法连接TDengine
Servlet basic principles and application of common API methods