上一篇 设计模式(Swift) - 1.MVC和代理 中涉及到了三点,类图,MVC和代理模式.git
单例限制了类的实例化,一个类只能实例化一个对象,全部对单例对象的引用都是指向了同一个对象. github
// 定义一个单例
final public class MySingleton {
static let shared = MySingleton()
private init() {} // 私有化构造方法(若是有须要也能够去掉)
}
// 使用
let s1 = MySingleton.shared
let s2 = MySingleton.shared
// let s3 = MySingleton() // 报错
dc.address(o: s1) // 0x000060400000e5e0
dc.address(o: s2) // 0x000060400000e5e0
复制代码
相比OC,swift中单例的实现简化了很多,swift中可使用let这种方式来保证线程安全.编程
经过备忘录模式咱们能够把某个对象保存在本地,并在适当的时候恢复出来. swift
Swift tips: Codable Codable是swift4推出来的新特性,全部基本类型都实现了 Codable 协议,只要自定义的对象遵照了该协议,就能够保存和恢复所须要的对象. 本质上Codable,就是Decodable和Encodable的集合. 具体拓展能够看这里Swift 4 踩坑之 Codable 协议设计模式
public typealias Codable = Decodable & Encodable
复制代码
我的用户信息的本地化存储,包括用户token啊之类的.安全
// MARK: - Originator(发起人)
public class UserInfo: Codable {
static let shared = UserInfo()
private init() {}
public var isLogin: Bool = false
public var account: String?
public var age: Int?
var description: String {
return "account:\(account ?? "为空"), age:\(age ?? 0)"
}
}
// MARK: - 备忘录(Memento): 负责存储Originator对象,swift中由Codable实现
// MARK: - 管理者(CareTaker)
public class UserInfoTaker {
public static let UserInforKey = "UserInfoKey"
private static let decoder = JSONDecoder()
private static let encoder = JSONEncoder()
private static let userDefaults = UserDefaults.standard
public static func save(_ p: UserInfo) throws {
let data = try encoder.encode(p)
userDefaults.set(data, forKey: UserInforKey)
}
public static func load() throws -> UserInfo {
guard let data = userDefaults.data(forKey: UserInforKey),
let userInfo = try? decoder.decode(UserInfo.self, from: data)
else {
throw Error.UserInfoNotFound
}
// decode生成的对象不是单例对象,须要转换成单例对象
// 若是你有更好的实现方式欢迎交流
let userInfoS = UserInfo.shared
userInfoS.account = userInfo.account
userInfoS.age = userInfo.age
userInfoS.isLogin = userInfo.isLogin
return userInfoS
}
public enum Error: String, Swift.Error {
case UserInfoNotFound
}
}
复制代码
let userInfo = UserInfo.shared
userInfo.isLogin = true
userInfo.account = "132154"
userInfo.age = 16
// 保存
do {
try UserInfoTaker.save(userInfo)
}catch {
print(error)
}
// 读取
do {
let newUserInfo = try UserInfoTaker.load()
dc.log(newUserInfo.description) // account:132154, age:16
dc.address(o: newUserInfo) // 0x000060000009a400
}catch {
print(error)
}
dc.log(userInfo.description) // account:132154, age:16
dc.address(o: userInfo) // 0x000060000009a400
复制代码
备忘录的最大好处就是能够恢复到特定的状态,但每次的读写操做须要消耗必定的系统资源,因此在某些场景下能够将单例模式和备忘录模式结合来统一管理操做数据.服务器
在平常开发中,咱们常常会碰到逻辑分支,咱们通常会用 if else或者switch去处理,但其实还有更好的方式: 策略模式. 策略模式抽象并封装业务细节,只给出相关的策略接口做为切换. app
实现一个商场打折的例子,分为三种状况,原价购买,按照一个折扣购买,满多少返现多少(满100减20).框架
能够先思考下再看代码.ui
// 策略协议
protocol DiscountStrategy {
// 支付价格
func payment(money: Double) -> Double
}
// 原价购买
class DiscountNormal: DiscountStrategy {
func payment(money: Double) -> Double {
return money
}
}
// 打折
class DiscountRebate: DiscountStrategy {
private let rebate: Double // 折扣
init(rebate: Double) {
self.rebate = rebate
}
func payment(money: Double) -> Double {
return money * rebate/10.0
}
}
// 返现
class DiscountReturn: DiscountStrategy {
private let moneyCondition: Double // 满
private let moneyReturn: Double // 返
init(moneyCondition: Double, moneyReturn: Double) {
self.moneyCondition = moneyCondition
self.moneyReturn = moneyReturn
}
func payment(money: Double) -> Double {
return money - (Double(Int(money/moneyCondition)) * moneyReturn)
}
}
// 策略枚举
enum PayMentStyle {
case normal
case rebate(rebate: Double)
case `return`(moneyCondition: Double, moneyReturn: Double)
}
// 策略管理
class DiscountContext {
var discountStrategy: DiscountStrategy?
init(style: PayMentStyle) {
switch style { // 对应的三种方式
case .normal:
discountStrategy = DiscountNormal()
case .rebate(rebate: let money):
discountStrategy = DiscountRebate(rebate: money)
case .return(moneyCondition: let condition, moneyReturn: let `return`):
discountStrategy = DiscountReturn(moneyCondition: condition, moneyReturn: `return`)
}
}
func getResult(money: Double) -> Double {
return discountStrategy?.payment(money: money) ?? 0
}
}
复制代码
let money: Double = 800
let normalPrice = DiscountContext(style: .normal).getResult(money: money)
let rebatePrice = DiscountContext(style: .rebate(rebate: 8)).getResult(money: money)
let returnPrice = DiscountContext(style: .return(moneyCondition: 100, moneyReturn: 20)).getResult(money: money)
print("正常价格:\(normalPrice)") // 正常价格:800.0
print("打八折:\(rebatePrice)") // 打八折:640.0
print("满100返20:\(returnPrice)") // 满100返20:640.0
复制代码
以上就是一个简单的策略模式实现,经过DiscountContext来管理每个DiscountStrategy.
主要讲了三种模式,只能实例化一个对象的单例模式,能够存储和恢复数据的备忘录模式以及能够在复杂业务逻辑下替代if else和switch语句的策略模式.
参考:
The Swift Programming Language (Swift 4.1)
若有疑问,欢迎留言 :-D