swift-原型模式

swift-原型模式,第1张

概述设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。GoF提出了23种设计模式,本系列将使用Swift语言来实现这些设计模式。 概述 通过复制一个已存在的对象来获得一个新的相同类型的对象被称作原型模式,在复制的过程中不需要关心被复制对象实现的接口或者类型。 原型模式Prototype具有如下优点: 隐藏了创建对象的实现细节 复制 *** 作不受子类构

设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。GoF提出了23种设计模式,本系列将使用Swift语言来实现这些设计模式。

概述

通过复制一个已存在的对象来获得一个新的相同类型的对象被称作原型模式,在复制的过程中不需要关心被复制对象实现的接口或者类型。

原型模式Prototype具有如下优点:

隐藏了创建对象的实现细节

复制 *** 作不受子类构造器改变影响

避免了重复创建对象产生的大量代码

简单来说,原型模式分为以下两种:

简单拷贝

登记拷贝

没有使用原型Prototype的拷贝代码是怎样的呢?我们需要通过访问

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 classpet:NSObject{ var name:String? var weigh:float? init(name:String,weigh:float){...} } classperson:NSObject{ var pet:Pet? var name:String? var height:float? init(name:String,height:float,pet:Pet){...} } letpet=Pet(name: "球球" ,weigh:2.0) letauthor=Person(name: "林欣达" ,height:173,pet:pet) var persons:[Person]=[Person]() for _ in 0...9{ persons.append(Person(name:author.name!,height:author.height!,pet:Pet(name:pet.name,weigh:pet.weigh))) }

简单形式拷贝

通过声明一个cloning协议来为需求方提供完全拷贝的方案

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 protocolcloning{ funcclone()->AnyObject } classpet:NSObject,cloning{ funcclone()->AnyObject{ return Pet(name:name!,weigh:weigh!) } } classperson:NSObject,cloning{ funcclone()->AnyObject{ return Person(name:name!,height:height!pet:pet?.clone()as!Pet) } } letauthor=Person(name: "林欣达" ,pet:Pet(name: "球球" ,weigh:2.0)) var persons:[Person]=[Person]() for _ in 0...9{ persons.append(author.clone()) }

简单点来说,原型模式在iOS开发中就是NScopying协议,通过实现这个协议完成对象和其成员对象的完全内存拷贝,也可以称为深拷贝。从这个角度而言,原型模式Prototype就是深拷贝的理论化

登记拷贝

登记拷贝实际上就是在简单拷贝的基础之上对这些clone对象进行管理

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 classCloneManager:NSObject{ staticletsharedManager=CloneManager() private var mapper:[String:cloning]=[String:cloning]() privateoverrIDeinit(){ super .init() } funcstore(prototype:cloning, for IDentifIEr:String){ mapper[IDentifIEr]=prototype } funcprototype( for IDentifIEr:String)->cloning?{ return mapper[IDentifIEr] } funcremove( with IDentifIEr:String){ mapper[IDentifIEr]=nil } } classVIEwController:UIVIEwController{ overrIDefuncvIEwDIDLoad(){ letclone=author.clone() CloneManager.sharedManager.store(clone, "CloneInstance" ) letstoredClone=CloneManager.sharedManager.prototype( for : "CloneInstance" ) if clone==storedClone{ print( "Storesuccess" ) } if clone!=author{ print( "Youcreateacopyinstanceofauthor" ) } CloneManager.sharedManager.remove( with : "CloneInstance" ) assert(CloneManager.sharedManager.prototype( for : "CloneInstance" )==nil) } }

总结

原型模式Prototype将对象和其成员对象的拷贝过程隐藏起来,只提供了一个简单的接口提供我们获取拷贝后的对象,是一种优雅而强大的设计。使用原型模式需要注意实现cloning的对象其成员对象也应该遵循这个协议提供简单的拷贝接口。

总结

以上是内存溢出为你收集整理的swift-原型模式全部内容,希望文章能够帮你解决swift-原型模式所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1055356.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存