当前位置:网站首页>原型模式(Prototype):Swift 实现
原型模式(Prototype):Swift 实现
2022-07-30 05:43:00 【大头鑫】
Prototype 原型模式
When we want to clone the instance itself, it may create some dependencies between the client and the original class, it will make the code be more complex. So we use “prototype” to compound the clone operation into the original class itself. And the clone operation will be easily.
当我们想要完全复制一个对象它本身时,很可能会在调用者和源类之间产生一些复杂当耦合关系。所以我们使用“原型”模式,将对象克隆操作整合在对象当源类之中。这样一来,克隆操作由特定的类自身决定,调用变得简洁。

// Prototype
protocol StorePrototype{
func clone() -> Store
}
// Concrete Prototype
class Store: StorePrototype {
var area: [Int] = [0, 0]
init(store: StorePrototype) {
if let s = store as? Store {
self.area = s.area
}
}
init() {
}
func clone() -> Store {
return Store(store: self)
}
}
// Sub Concrete Prototype
class BookStore: Store {
var bookSelfCount = 0
init(bookStore: StorePrototype) {
super.init(store: bookStore)
if let s = bookStore as? BookStore {
self.bookSelfCount = s.bookSelfCount
}
}
override init() {
super.init()
}
override func clone() -> Store {
return BookStore(bookStore: self)
}
}
// Sub Concrete Prototype
class FlowerStore: Store {
var flowers = ["Sun Flower", "Rose", "Lily"]
init(flowerStore: StorePrototype) {
super.init(store: flowerStore)
if let s = flowerStore as? FlowerStore {
self.flowers = s.flowers
}
}
override init() {
super.init()
}
override func clone() -> Store {
return FlowerStore(flowerStore: self)
}
}
let store = Store()
let obj = FlowerStore()
let copyStore = store.clone()
let copyObj = obj.clone()
// Now it did the deep copy. It copy the whole instance "store" to "copyStore", and copy the whole instace "obj" to copyObj.
边栏推荐
- Obtain geographic location and coordinates according to ip address (offline method)
- The most powerful and most commonly used SQL statements in history
- 【SQL】first_value 应用场景 - 首单 or 复购
- C#下大批量一键空投实现
- GraphQL(一)基础介绍及应用示例
- Using custom annotations, statistical method execution time
- FastAPI Quick Start
- sql concat() function
- Remember a Mailpress plugin RCE vulnerability recurrence
- MySQL - 函数及约束命令
猜你喜欢
随机推荐
Kotlin协程的简单用法:1、GlobalScope(不建议使用);2、lifecycleScope、viewModelScope(建议使用);
C#预定义数据类型简介
Student management system
Reasons and solutions for Invalid bound statement (not found)
shardingsphere 分库分表及配置示例
使用PyQt5为YoloV5添加界面(一)
MySQL 5.7 安装教程(全步骤、保姆级教程)
MYSQL一站式学习,看完即学完
十六、Kotlin进阶学习:协程详细学习。
Function functional interface and application
Oracle数据库SQL优化详解
Nodejs PM2 monitoring and alarm email (2)
Jdbc & Mysql timeout analysis
使用kotlin扩展插件/依赖项简化代码(在最新版本4.0以后,此插件已被弃用,故请选择性学习,以了解为主。)
MySQL 5.7 installation tutorial (all steps, nanny tutorials)
C#中对委托的理解和使用
misc-log analysis of CTF
Calendar类的习题
Use kotlin to extend plugins/dependencies to simplify code (after the latest version 4.0, this plugin has been deprecated, so please choose to learn, mainly to understand.)
[HCTF 2018]admin









