蒋正义的修炼之路


  • 首页

  • 归档

  • 标签

协调器模式

发表于 2019-12-10

协调器模式(Coordinator Pattern)

协调器模式是一种结构型设计模式,用来组织viewcontroller之间的跳转逻辑。它包含以下部分

  1. coordinator:定义了所有concrete coordinators必须实现的方法和属性。具体来说,它定义关系属性,子级和router。它还定义了呈现方法,present和dismiss。通过持有coordinator protocol而不是直接持有concrete coordinators,你可以将父协调器与其子协调器解耦。这也使父协调员可以在单个属性中保留各种具体的子协调员,即children
  2. concrete coordinator:实现了coordinator protocol。它知道如何创建具体的view controller以及view controller的显示顺序。
  3. router:一种协议,定义了所有 concrete router必须实现的方法。具体来说,它定义了用于显示和关闭视图控制器的present和dismiss方法
  4. concrete router:知道如何显示view controller,但不知道在显示什么或接下来将显示哪个view controller。相反,coordinator告诉router要显示哪个view controller
  5. concrete view controllers:mvc中的view controller,他们不知道其他的view controller。他们是coordinator的代理。

使用举例

1.创建Router protocol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public protocol Router: class {
func present(_ viewController: UIViewController, animated: Bool)
func present(_ viewController: UIViewController,
animated: Bool,
onDismissed: (()->Void)?)
func dismiss(animated: Bool)
}
extension Router {
public func present(_ viewController: UIViewController,
animated: Bool) {
present(viewController, animated: animated, onDismissed: nil)
}
}

2.创建Concrete Router

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class NavigationRouter: NSObject {
private let navigationController: UINavigationController
private let routerRootController: UIViewController?
private var onDismissForViewController:
[UIViewController: (() -> Void)] = [:]
public init(navigationController: UINavigationController) {
self.navigationController = navigationController
self.routerRootController = navigationController.viewControllers.first
super.init()
navigationController.delegate = self
}
}
// MARK: - Router
extension NavigationRouter: Router {
public func present(_ viewController: UIViewController,
animated: Bool,
onDismissed: (() -> Void)?) {
onDismissForViewController[viewController] = onDismissed
navigationController.pushViewController(viewController,
animated: animated)
}
public func dismiss(animated: Bool) {
guard let routerRootController = routerRootController else {
navigationController.popToRootViewController(animated: animated)
return
}
performOnDismissed(for: routerRootController)
navigationController.popToViewController(routerRootController,
animated: animated)
}
private func performOnDismissed(for viewController: UIViewController) {
guard let onDismiss = onDismissForViewController[viewController]
else {
return
}
onDismiss()
onDismissForViewController[viewController] = nil
}
}
// MARK: - UINavigationControllerDelegate
extension NavigationRouter: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool) {
guard let dismissedViewController = navigationController.transitionCoordinator?.viewController(forKey: .from),
!navigationController.viewControllers.contains(dismissedViewController) else { return }
performOnDismissed(for: dismissedViewController)
}
}

3.创建Coordinator protocol

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
32
33
34
35
36
37
public protocol Coordinator: class {
var children: [Coordinator] { get set }
var router: Router { get }
func present(animated: Bool, onDismissed: (() -> Void)?)
func dismiss(animated: Bool)
func presentChild(_ child: Coordinator,
animated: Bool,
onDismissed: (() -> Void)?)
}
extension Coordinator {
public func dismiss(animated: Bool) {
router.dismiss(animated: true)
}
public func presentChild(_ child: Coordinator,
animated: Bool,
onDismissed: (() -> Void)? = nil) {
children.append(child)
child.present(animated: animated, onDismissed: { [weak self, weak child] in
guard let self = self, let child = child else { return }
self.removeChild(child)
onDismissed?()
})
}
private func removeChild(_ child: Coordinator) {
guard let index = children.firstIndex(where: { $0 === child })
else {
return
}
children.remove(at: index)
}
}

4.创建Concrete Coordinator

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public class HowToCodeCoordinator: Coordinator {
// MARK: - Instance Properties
public var children: [Coordinator] = []
public let router: Router
private lazy var stepViewControllers = [
StepViewController.instantiate(
delegate: self,
buttonColor: UIColor(red: 0.96, green: 0, blue: 0.11, alpha: 1),
text: "When I wake up, well, I'm sure I'm gonna be\n\n" +
"I'm gonna be the one writin' code for you",
title: "I wake up"),
StepViewController.instantiate(
delegate: self,
buttonColor: UIColor(red: 0.93, green: 0.51, blue: 0.07, alpha: 1),
text: "When I go out, well, I'm sure I'm gonna be\n\n" +
"I'm gonna be the one thinkin' bout code for you",
title: "I go out"),
StepViewController.instantiate(
delegate: self,
buttonColor: UIColor(red: 0.23, green: 0.72, blue: 0.11, alpha: 1.0),
text: "Cause' I would code five hundred lines\n\n" +
"And I would code five hundred more",
title: "500 lines"),
StepViewController.instantiate(
delegate: self,
buttonColor: UIColor(red: 0.18, green: 0.29, blue: 0.80, alpha: 1.0),
text: "To be the one that wrote a thousand lines\n\n" +
"To get this code shipped out the door!",
title: "Ship it!")
]
private lazy var startOverViewController =
StartOverViewController.instantiate(delegate: self)
// MARK: - Object Lifecycle
public init(router: Router) {
self.router = router
}
// MARK: - Coordinator
public func present(animated: Bool, onDismissed: (() -> Void)?) {
let viewController = stepViewControllers.first!
router.present(viewController, animated: animated, onDismissed: onDismissed)
}
}
// MARK: - StepViewControllerDelegate
extension HowToCodeCoordinator: StepViewControllerDelegate {
public func stepViewControllerDidPressNext(_ controller: StepViewController) {
if let viewController = stepViewController(after: controller) {
router.present(viewController, animated: true)
} else {
router.present(startOverViewController, animated: true)
}
}
private func stepViewController(after controller: StepViewController) -> StepViewController? {
guard let index = stepViewControllers.firstIndex(where: { $0 === controller }),
index < stepViewControllers.count - 1 else { return nil }
return stepViewControllers[index + 1]
}
}
// MARK: - StartOverViewControllerDelegate
extension HowToCodeCoordinator: StartOverViewControllerDelegate {
public func startOverViewControllerDidPressStartOver(_ controller: StartOverViewController) {
router.dismiss(animated: true)
}
}

5.使用协调者模式

1
2
3
4
5
6
7
8
9
10
11
let homeViewController = HomeViewController.instantiate()
let navigationController = UINavigationController(rootViewController: homeViewController)
let router = NavigationRouter(navigationController: navigationController)
let coordinator = HowToCodeCoordinator(router: router)
homeViewController.onButtonPressed = { [weak coordinator] in
coordinator?.present(animated: true, onDismissed: nil)
}
PlaygroundPage.current.liveView = navigationController

其他例子

  1. 在tableview中使用:https://blog.csdn.net/weixin_33768481/article/details/87940599
  2. 学习日本汉字的app:https://blog.csdn.net/kmyhy/article/details/80770184
  3. 使用Coordinator提高VC/ViewModel复用性:https://www.jianshu.com/p/e8fc65bcf1c8
  4. 视频学习地址:https://www.jianshu.com/p/cdd96b462ffb
  5. 基于ReSwift和App Coordinator的iOS架构:https://www.jianshu.com/p/42766da9578e

责任链模式

发表于 2019-12-09

责任链模式(Chain-of-Responsibility Pattern)

责任链模式是一种行为模式,它让事件被多个处理器中其中一个处理。包含以下3部分:

  1. client:接受事件并将事件传递给处理 handler protocol的实例。事件可以是简单的,仅具有属性的结构,也可以是复杂的对象,例如复杂的用户操作。
  2. handler protocol:定义了handler必须实现的属性和方法。也可以使用基类
  3. concrete handler:实现handler protocol中的方法,被client直接持有。收到事件后,它首先尝试处理它。如果无法执行此操作,则将事件传递给下一个handler

使用举例

使用此模式实现一个自动售货机

1.声明模型

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// MARK: - Models
public class Coin {
public class var standardDiameter: Double {
return 0
}
public class var standardWeight: Double {
return 0
}
public var centValue: Int { return 0 }
public final var dollarValue: Double { return Double(centValue) / 100 }
public final let diameter: Double
public final let weight: Double
public required init(diameter: Double, weight: Double) {
self.diameter = diameter
self.weight = weight
}
public convenience init() {
let diameter = type(of: self).standardDiameter
let weight = type(of: self).standardWeight
self.init(diameter: diameter, weight: weight)
}
}
extension Coin: CustomStringConvertible {
public var description: String {
return String(format:
"%@ {diameter: %0.3f, dollarValue: $%0.2f, weight: %0.3f}",
"\(type(of: self))", diameter, dollarValue, weight)
}
}
public class Penny: Coin {
public override class var standardDiameter: Double {
return 0.75
}
public override class var standardWeight: Double {
return 2.5
}
public override var centValue: Int { return 1 }
}
public class Nickel: Coin {
public override class var standardDiameter: Double {
return 0.835
}
public override class var standardWeight: Double {
return 5.0
}
public override var centValue: Int { return 5 }
}
public class Dime: Coin {
public override class var standardDiameter: Double {
return 0.705
}
public override class var standardWeight: Double {
return 2.268
}
public override var centValue: Int { return 10 }
}
public class Quarter: Coin {
public override class var standardDiameter: Double {
return 0.955
}
public override class var standardWeight: Double {
return 5.670
}
public override var centValue: Int { return 25 }
}

2.声明HandlerProtocol

1
2
3
4
5
// MARK: - HandlerProtocol
public protocol CoinHandlerProtocol {
var next: CoinHandlerProtocol? { get }
func handleCoinValidation(_ unknownCoin: Coin) -> Coin?
}

3.声明Concrete Handler

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class CoinHandler {
public var next: CoinHandlerProtocol?
public let coinType: Coin.Type
public let diameterRange: ClosedRange<Double>
public let weightRange: ClosedRange<Double>
public init(coinType: Coin.Type,
diameterVariation: Double = 0.01,
weightVariation: Double = 0.05) {
self.coinType = coinType
let standardDiameter = coinType.standardDiameter
self.diameterRange =
(1-diameterVariation)*standardDiameter ...
(1+diameterVariation)*standardDiameter
let standardWeight = coinType.standardWeight
self.weightRange =
(1-weightVariation)*standardWeight ...
(1+weightVariation)*standardWeight
}
}
extension CoinHandler: CoinHandlerProtocol {
public func handleCoinValidation(_ unknownCoin: Coin) ->
Coin? {
guard let coin = createCoin(from: unknownCoin) else {
return next?.handleCoinValidation(unknownCoin)
}
return coin
}
private func createCoin(from unknownCoin: Coin) -> Coin? {
print("Attempt to create \(coinType)")
guard diameterRange.contains(unknownCoin.diameter) else {
print("Invalid diameter")
return nil
}
guard weightRange.contains(unknownCoin.weight) else {
print("Invalid weight")
return nil
}
let coin = coinType.init(diameter: unknownCoin.diameter,
weight: unknownCoin.weight)
print("Created \(coin)")
return coin
}
}

4.声明Client

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
public class VendingMachine {
public let coinHandler: CoinHandler
public var coins: [Coin] = []
public init(coinHandler: CoinHandler) {
self.coinHandler = coinHandler
}
public func insertCoin(_ unknownCoin: Coin) {
guard let coin = coinHandler.handleCoinValidation(unknownCoin)
else {
print("Coin rejected: \(unknownCoin)")
return
}
print("Coin Accepted: \(coin)")
coins.append(coin)
let dollarValue = coins.reduce(0, { $0 + $1.dollarValue })
print("Coins Total Value: $\(dollarValue)")
let weight = coins.reduce(0, { $0 + $1.weight })
print("Coins Total Weight: \(weight) g")
print("")
}
}

5.使用责任链模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// MARK: - Example
let pennyHandler = CoinHandler(coinType: Penny.self)
let nickleHandler = CoinHandler(coinType: Nickel.self)
let dimeHandler = CoinHandler(coinType: Dime.self)
let quarterHandler = CoinHandler(coinType: Quarter.self)
pennyHandler.next = nickleHandler
nickleHandler.next = dimeHandler
dimeHandler.next = quarterHandler
let vendingMachine = VendingMachine(coinHandler: pennyHandler)
let penny = Penny()
vendingMachine.insertCoin(penny)
let quarter = Coin(diameter: Quarter.standardDiameter,
weight: Quarter.standardWeight)
vendingMachine.insertCoin(quarter)
let invalidDime = Coin(diameter: Quarter.standardDiameter,
weight: Dime.standardWeight)
vendingMachine.insertCoin(invalidDime)

其他例子

  1. OC使用部门管理权限:https://segmentfault.com/a/1190000011449768
  2. 游戏中抵抗攻击:https://my.oschina.net/daguoshi/blog/495573
  3. 快递:http://jackliu17.github.io/2016/06/06/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%B4%A3%E4%BB%BB%E9%93%BE/
  4. 责任链模式在 iOS 中的应用:https://blog.csdn.net/kuyeluofan/article/details/80467441

命令模式

发表于 2019-12-09

命令模式(Command Pattern)

命令模式是一种行为模式,将执行操作的信息封装到命令对象中。它包含以下3个类型:

  1. invoker:储存和执行命令
  2. command:将行为封装成对象
  3. receiver:command所作用的对象

使用举例

1.创建Receiver

1
2
3
4
// MARK: - Receiver
public class Door {
public var isOpen = false
}

2.创建Command

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DoorCommand {
public let door: Door
public init(_ door: Door) {
self.door = door
}
public func execute() { }
}
public class OpenCommand: DoorCommand {
public override func execute() {
print("opening the door...")
door.isOpen = true
}
}
public class CloseCommand: DoorCommand {
public override func execute() {
print("closing the door...")
door.isOpen = false
}
}

3.创建invoker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// MARK: - Invoker
public class Doorman {
public let commands: [DoorCommand]
public let door: Door
public init(door: Door) {
let commandCount = arc4random_uniform(10) + 1
self.commands = (0 ..< commandCount).map { index in
return index % 2 == 0 ?
OpenCommand(door) : CloseCommand(door)
}
self.door = door
}
public func execute() {
print("Doorman is...")
commands.forEach { $0.execute() }
}
}

4.使用命令模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// MARK: - Example
public let isOpen = true
print("You predict the door will be " +
"\(isOpen ? "open" : "closed").")
print("")
let door = Door()
let doorman = Doorman(door: door)
doorman.execute()
print("")
if door.isOpen == isOpen {
print("You were right! :]")
} else {
print("You were wrong :[")
}
print("The door is \(door.isOpen ? "open" : "closed").")

其他例子

  1. 改变一个视图的明亮程度:http://jackliu17.github.io/2016/06/03/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E5%91%BD%E4%BB%A4/
  2. 与普通写法的比较:https://yq.aliyun.com/articles/37261
  3. 撤销操作:https://juejin.im/post/5844c329ac502e006ba97570
  4. 屏幕变量和撤销:https://www.jianshu.com/p/c62e1bc04bf1

组合模式

发表于 2019-12-09

组合模式(Composite Pattern)

组合模式是一种结构型设计模式,将一组对象组合成树状结构,以便可以像对待一个对象一样来对其进行操作,它包含以下三个类型:

  1. component protocol:确保树中的所有构造都可以以相同的方式处理
  2. leaf:树的组成部分,没有子元素
  3. composite:持有leaf对象和composites的容器

UIView就使用到了组合模式

使用举例

使用组合模式做一个文件系统

1.创建component protocol

1
2
3
4
protocol File {
var name: String { get set }
func open()
}

2.创建leaf objects

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
final class eBook: File {
var name: String
var author: String
init(name: String, author: String) {
self.name = name
self.author = author
}
func open() {
print("Opening \(name) by \(author) in iBooks...\n")
}
}
final class Music: File {
var name: String
var artist: String
init(name: String, artist: String) {
self.name = name
self.artist = artist
}
func open() {
print("Playing \(name) by \(artist) in iTunes...\n")
}
}

3.创建composite对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final class Folder: File {
var name: String
lazy var files: [File] = []
init(name: String) {
self.name = name
}
func addFile(file: File) {
self.files.append(file)
}
func open() {
print("Displaying the following files in \(name)...")
for file in files {
print(file.name)
}
print("\n")
}
}

4.使用组合模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let psychoKiller = Music(name: "Psycho Killer", artist: "The Talking Heads")
let rebelRebel = Music(name: "Rebel Rebel", artist: "David Bowie")
let blisterInTheSun = Music(name: "Blister in the Sun", artist: "Violent Femmes")
let justKids = eBook(name: "Just Kids", author: "Patti Smith")
let documents = Folder(name: "Documents")
let musicFolder = Folder(name: "Great 70s Music")
documents.addFile(file: musicFolder)
documents.addFile(file: justKids)
musicFolder.addFile(file: psychoKiller)
musicFolder.addFile(file: rebelRebel)
blisterInTheSun.open()
justKids.open()
documents.open()
musicFolder.open()

其他例子

  1. 公司结构:https://segmentfault.com/a/1190000008151403
  2. 菜单:http://www.cocoachina.com/articles/18319
  3. 树状结构和文件系统:https://www.cnblogs.com/goodboy-heyang/p/5226090.html

中介者模式

发表于 2019-11-29

中介者模式(Mediator Pattern)

中介者模式是一种行为模式,封装了对象间的通信方式,它包含了四个类型:

  1. colleagues:需要互相交流的对象。他们实现了colleague protocol。
  2. colleague protocol:定义了每个colleague必须实现的方法和属性。
  3. mediator:控制colleague之间交流的对象。它实现了mediator protocol。
  4. mediator protocol:定义了mediator必须实现的方法和属性。

每个colleague都通过mediator protocol持有mediator的引用。每个colleague都通过mediator来相互交流,而不是直接交流。

每个colleague都可能通过mediator发送或接收消息。

跟多播委托模式相似,但是有不同之处

使用举例

创建mediator基类

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
open class Mediator<ColleagueType> {
private class ColleagueWrapper {
var strongColleague: AnyObject?
weak var weakColleague: AnyObject?
var colleague: ColleagueType? {
return (weakColleague ?? strongColleague) as? ColleagueType
}
init(weakColleague: ColleagueType) {
self.strongColleague = nil
self.weakColleague = weakColleague as AnyObject
}
init(strongColleague: ColleagueType) {
self.strongColleague = strongColleague as AnyObject
self.weakColleague = nil
}
}
// MARK: - Instance Properties
private var colleagueWrappers: [ColleagueWrapper] = []
public var colleagues: [ColleagueType] {
var colleagues: [ColleagueType] = []
colleagueWrappers = colleagueWrappers.filter {
guard let colleague = $0.colleague else { return false }
colleagues.append(colleague)
return true
}
return colleagues
}
// MARK: - Object Lifecycle
public init() { }
// MARK: - Colleague Management
public func addColleague(_ colleague: ColleagueType,
strongReference: Bool = true) {
let wrapper: ColleagueWrapper
if strongReference {
wrapper = ColleagueWrapper(strongColleague: colleague)
} else {
wrapper = ColleagueWrapper(weakColleague: colleague)
}
colleagueWrappers.append(wrapper)
}
public func removeColleague(_ colleague: ColleagueType) {
guard let index = colleagues.index(where: {
($0 as AnyObject) === (colleague as AnyObject)
}) else { return }
colleagueWrappers.remove(at: index)
}
public func invokeColleagues(closure: (ColleagueType) -> Void) {
colleagues.forEach(closure)
}
public func invokeColleagues(by colleague: ColleagueType,
closure: (ColleagueType) -> Void) {
colleagues.forEach {
guard ($0 as AnyObject) !== (colleague as AnyObject)
else { return }
closure($0)
}
}
}

创建colleague protocol

1
2
3
4
5
// MARK: - Colleague Protocol
public protocol Colleague: class {
func colleague(_ colleague: Colleague?,
didSendMessage message: String)
}

创建mediator protocol

1
2
3
4
5
// MARK: - Mediator Protocol
public protocol MediatorProtocol: class {
func addColleague(_ colleague: Colleague)
func sendMessage(_ message: String, by colleague: Colleague)
}

创建colleague

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// MARK: - Colleague
public class Musketeer {
public var name: String
public weak var mediator: MediatorProtocol?
public init(mediator: MediatorProtocol, name: String) {
self.mediator = mediator
self.name = name
mediator.addColleague(self)
}
public func sendMessage(_ message: String) {
print("\(name) sent: \(message)")
mediator?.sendMessage(message, by: self)
}
}
extension Musketeer: Colleague {
public func colleague(_ colleague: Colleague?,
didSendMessage message: String) {
print("\(name) received: \(message)")
}
}

创建mediator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// MARK: - Mediator
public class MusketeerMediator: Mediator<Colleague> {
}
extension MusketeerMediator: MediatorProtocol {
public func addColleague(_ colleague: Colleague) {
self.addColleague(colleague, strongReference: true)
}
public func sendMessage(_ message: String,
by colleague: Colleague) {
invokeColleagues(by: colleague) {
$0.colleague(colleague, didSendMessage: message)
}
}
}

使用中介者模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// MARK: - Example
let mediator = MusketeerMediator()
let athos = Musketeer(mediator: mediator, name: "Athos")
let porthos = Musketeer(mediator: mediator, name: "Porthos")
let aramis = Musketeer(mediator: mediator, name: "Aramis")
athos.sendMessage("One for all...!")
print("")
porthos.sendMessage("and all for one...!")
print("")
aramis.sendMessage("Unus pro omnibus, omnes pro uno!")
print("")
mediator.invokeColleagues() {
$0.colleague(nil, didSendMessage: "Charge!")
}

其他例子

  1. 中介者模式与组件化:http://5mengqi.cc/blogs/talk-about-the-mediator-pattern/
  2. oc中的中介者模式:http://jackliu17.github.io/2016/06/06/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%AD%E4%BB%8B%E8%80%85/
  3. 控制器切换中的中介者模式:https://www.jianshu.com/p/f2b4379c3b16

享元模式

发表于 2019-11-29

享元模式(Flyweight Pattern)

享元模式是一种结构性设计模式,可以最大程度地减少内存使用和处理。

此模式提供的对象均共享相同的基础数据,从而节省了内存。它们通常是不变的。

享元模式具有称为flyweights的对象,以及返回它们的静态方法

享元模式是单例模式的变体,在享元模式中,通常有多个相同类的不同对象。

使用举例

享元模式在UIKit中使用非常普遍,UIColor,UIFont,UITableViewCell都是使用享元模式的类。

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
32
33
34
35
36
import UIKit
let red = UIColor.red
let red2 = UIColor.red
print(red === red2) // proves this is a flyweight
let color = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
let color2 = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
print(color === color2) // proves this is NOT a flyweight
extension UIColor {
public static var colorStore: [String: UIColor] = [:]
public class func rgba(_ red: CGFloat,
_ green: CGFloat,
_ blue: CGFloat,
_ alpha: CGFloat) -> UIColor {
let key = "\(red)\(green)\(blue)\(alpha)"
if let color = colorStore[key] {
return color
}
let color = UIColor(red: red,
green: green,
blue: blue,
alpha: alpha)
colorStore[key] = color
return color
}
}
let flyColor = UIColor.rgba(1, 0, 0, 1)
let flyColor2 = UIColor.rgba(1, 0, 0, 1)
print(flyColor === flyColor2) // proves this is a flyweight class method

其他例子

  1. OC中的享元模式:https://www.jianshu.com/p/e3eb1fa44f83
  2. 咖啡例子:http://jackliu17.github.io/2016/06/05/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%BA%AB%E5%85%83/
  3. 在屏幕中画多个花:https://segmentfault.com/a/1190000012507640

外观模式

发表于 2019-11-28

外观模式(Facade Pattern)

外观模式是一种结构模式,给一个复杂的系统提供一键简单的接口,它包含两种类型:

  1. facade:提供了简单的接口来跟系统交互,这允许开发者使用外观,而不是了解系统中的多个类并与之交互
  2. dependencies:被facade持有,每个dependency负责一个巨大任务中的一部分

使用举例

一个购物系统可能包含了消费者,产品,库存,运输订单等部件。我们不需要消费者理解每个部件和他们之间如何交互,只需要提供一个facade来暴露一些常见的方法,比如下订单和完成订单。

创建dependencies

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// MARK: - Dependencies
public struct Customer {
public let identifier: String
public var address: String
public var name: String
}
extension Customer: Hashable {
public var hashValue: Int {
return identifier.hashValue
}
public static func ==(lhs: Customer,
rhs: Customer) -> Bool {
return lhs.identifier == rhs.identifier
}
}
public struct Product {
public let identifier: String
public var name: String
public var cost: Double
}
extension Product: Hashable {
public var hashValue: Int {
return identifier.hashValue
}
public static func ==(lhs: Product,
rhs: Product) -> Bool {
return lhs.identifier == rhs.identifier
}
}
public class InventoryDatabase {
public var inventory: [Product: Int] = [:]
public init(inventory: [Product: Int]) {
self.inventory = inventory
}
}
public class ShippingDatabase {
public var pendingShipments: [Customer: [Product]] = [:]
}

创建facade

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
32
// MARK: - Facade
public class OrderFacade {
public let inventoryDatabase: InventoryDatabase
public let shippingDatabase: ShippingDatabase
public init(inventoryDatabase: InventoryDatabase,
shippingDatabase: ShippingDatabase) {
self.inventoryDatabase = inventoryDatabase
self.shippingDatabase = shippingDatabase
}
public func placeOrder(for product: Product,
by customer: Customer) {
print("Place order for '\(product.name)' by '\(customer.name)'")
let count = inventoryDatabase.inventory[product, default: 0]
guard count > 0 else {
print("'\(product.name)' is out of stock!")
return
}
inventoryDatabase.inventory[product] = count - 1
var shipments =
shippingDatabase.pendingShipments[customer, default: []]
shipments.append(product)
shippingDatabase.pendingShipments[customer] = shipments
print("Order placed for '\(product.name)' " +
"by '\(customer.name)'")
}
}

使用外观模式

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
// MARK: - Example
let rayDoodle = Product(
identifier: "product-001",
name: "Ray's doodle",
cost: 0.25)
let vickiPoodle = Product(
identifier: "product-002",
name: "Vicki's prized poodle",
cost: 1000)
let inventoryDatabase = InventoryDatabase(
inventory: [rayDoodle: 50, vickiPoodle : 1]
)
let orderFacade = OrderFacade(
inventoryDatabase: inventoryDatabase,
shippingDatabase: ShippingDatabase())
let customer = Customer(
identifier: "customer-001",
address: "1600 Pennsylvania Ave, Washington, DC 20006",
name: "Johnny Appleseed")
orderFacade.placeOrder(for: vickiPoodle, by: customer)

其他例子

  1. SDWebImage中使用到了外观模式:https://juejin.im/post/5b6c0878e51d45348a3028d2
  2. 买汽车中的外观模式:https://www.jianshu.com/p/80f0455a5b08
  3. app登录系统中的外观模式:https://www.jianshu.com/p/d04b47cfa1cd

多播委托模式

发表于 2019-11-28

多播委托模式(Multicast Delegate Pattern)

多播委托模式一种行为模式,是代理模式的变体。它能让你创建一对多的代理关系,而普通的代理模式只有一对一的关系。它包含以下四个类型:

  1. object needing a delegate(delegating object):持有一个或多个代理的对象
  2. delegate protocol:定义了一个代理需要实现的方法
  3. delegate(s):实现了delegate protocol的多个对象
  4. multicast delegate:持有多个代理的辅助类,能在有事件发生时通知每个代理

代理模式和多播委托模式做大的区别就在multicast delegate的存在。

使用举例

创建multicast delegate

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class MulticastDelegate<ProtocolType> {
// MARK: - DelegateWrapper
private class DelegateWrapper {
weak var delegate: AnyObject?
init(_ delegate: AnyObject) {
self.delegate = delegate
}
}
// MARK: - Instance Properties
private var delegateWrappers: [DelegateWrapper]
public var delegates: [ProtocolType] {
delegateWrappers = delegateWrappers
.filter { $0.delegate != nil }
return delegateWrappers.map
{ $0.delegate! } as! [ProtocolType]
}
// MARK: - Object Lifecycle
public init(delegates: [ProtocolType] = []) {
delegateWrappers = delegates.map {
DelegateWrapper($0 as AnyObject)
}
}
// MARK: - Delegate Management
public func addDelegate(_ delegate: ProtocolType) {
let wrapper = DelegateWrapper(delegate as AnyObject)
delegateWrappers.append(wrapper)
}
public func removeDelegate(_ delegate: ProtocolType) {
guard let index = delegateWrappers.index(where: {
$0.delegate === (delegate as AnyObject)
}) else {
return
}
delegateWrappers.remove(at: index)
}
public func invokeDelegates(_ closure: (ProtocolType) -> ()) {
delegates.forEach { closure($0) }
}
}

创建delegate protocol

1
2
3
4
5
// MARK: - Delegate Protocol
public protocol EmergencyResponding {
func notifyFire(at location: String)
func notifyCarCrash(at location: String)
}

创建delegates

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
// MARK: - Delegates
public class FireStation: EmergencyResponding {
public func notifyFire(at location: String) {
print("Firefighters were notified about a fire at "
+ location)
}
public func notifyCarCrash(at location: String) {
print("Firefighters were notified about a car crash at "
+ location)
}
}
public class PoliceStation: EmergencyResponding {
public func notifyFire(at location: String) {
print("Police were notified about a fire at "
+ location)
}
public func notifyCarCrash(at location: String) {
print("Police were notified about a car crash at "
+ location)
}
}

创建delegating object

1
2
3
4
5
// MARK: - Delegating Object
public class DispatchSystem {
let multicastDelegate =
MulticastDelegate<EmergencyResponding>()
}

使用多播委托模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// MARK: - Example
let dispatch = DispatchSystem()
var policeStation: PoliceStation! = PoliceStation()
var fireStation: FireStation! = FireStation()
dispatch.multicastDelegate.addDelegate(policeStation)
dispatch.multicastDelegate.addDelegate(fireStation)
dispatch.multicastDelegate.invokeDelegates {
$0.notifyFire(at: "Ray's house!")
}
print("")
fireStation = nil
dispatch.multicastDelegate.invokeDelegates {
$0.notifyCarCrash(at: "Ray's garage!")
}

其他例子

  1. 使用多播委托模式管理页面主题颜色:https://juejin.im/post/5bd6842f6fb9a05d0045f925
  2. OC中构造多播代理:https://www.jianshu.com/p/8f2b9d6b9c85

状态模式

发表于 2019-11-27

状态模式(State Pattern)

状态模式是一种行为模式,能让对象通过修改他们的“状态”,在运行时改变自己的行为。“状态”是指描述给定对象在给定时间如何行为的数据集。

状态模式包含以下三种类型:

  1. context:具有当前状态且其行为会发生变化的对象。
  2. state protocol:定义了必需的方法和属性。开发人员通常用基类代替协议。这样,他们就可以在基类中定义属性。

    即使使用了基类,也不能直接实例化它。相反,它的定义仅是为了能够被子类化。

  3. concrete state:遵循state protocol或继承自基类。context会持有它的当前状态,但不知道具体的状态类型。context会使用多态来改变行为:concrete state定义了context的行为。如果你想要一个新的行为,定义一个新的concrete state。

应该在哪里修改当前状态呢?是在context里修改?还是在concrete state修改?还是在其他什么地方修改呢?状态模式并没有告诉你应该在哪里写状态修改逻辑,这视实际情况决定。

什么时候应该使用状态模式

使用状态模式来创建一个系统,该系统在其生命周期内会在两个或多个状态之间进行更改。状态可以限制数量(“封闭”集),也可以不受限制(“开放”集)。例如,可以使用一组封闭的“交通信号灯状态”来定义交通信号灯。在最简单的情况下,它会从绿色变为黄色,再变成红色,最后变回绿色。

一个动画引擎可以定义为一组开放的“动画状态”。它具有无限的旋转,平移和其他动画。

开放式和封闭式的状态模式的都使用多态来更改行为。结果,您通常可以使用此模式来消除switch和if-else语句。

无需在context中管理复杂的状态,而是将调用传递到当前状态中。如果你有一个包含多个switch或if-else语句的类,请尝试使用状态模式来定义它。这样你就可能会创建一个更灵活,更容易维护的系统。

状态模式和策略模式的区别

策略模式更多的是解决不同状态下,单行为的变化;而状态模式则是解决不同状态下多行为的变化。

使用举例

实现上文提到过的交通灯系统

1.定义context

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// MARK: - Context
public class TrafficLight: UIView {
// MARK: - Instance Properties
public private(set) var canisterLayers: [CAShapeLayer] = []
public private(set) var currentState: TrafficLightState
public private(set) var states: [TrafficLightState]
// MARK: - Object Lifecycle
@available(*, unavailable,
message: "Use init(canisterCount: frame:) instead")
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
public init(canisterCount: Int = 3,
frame: CGRect =
CGRect(x: 0, y: 0, width: 160, height: 420),
states: [TrafficLightState]) {
guard !states.isEmpty else {
fatalError("states should not be empty")
}
self.currentState = states.first!
self.states = states
super.init(frame: frame)
backgroundColor =
UIColor(red: 0.86, green: 0.64, blue: 0.25, alpha: 1)
createCanisterLayers(count: canisterCount)
transition(to: currentState)
}
private func createCanisterLayers(count: Int) {
let paddingPercentage: CGFloat = 0.2
let yTotalPadding = paddingPercentage * bounds.height
let yPadding = yTotalPadding / CGFloat(count + 1)
let canisterHeight = (bounds.height - yTotalPadding) / CGFloat(count)
let xPadding = (bounds.width - canisterHeight) / 2.0
var canisterFrame = CGRect(x: xPadding,
y: yPadding,
width: canisterHeight,
height: canisterHeight)
for _ in 0 ..< count {
let canisterShape = CAShapeLayer()
canisterShape.path = UIBezierPath(ovalIn: canisterFrame).cgPath
canisterShape.fillColor = UIColor.black.cgColor
layer.addSublayer(canisterShape)
canisterLayers.append(canisterShape)
canisterFrame.origin.y += (canisterFrame.height + yPadding)
}
}
public func transition(to state: TrafficLightState) {
removeCanisterSublayers()
currentState = state
currentState.apply(to: self)
nextState.apply(to: self, after: currentState.delay)
}
private func removeCanisterSublayers() {
canisterLayers.forEach {
$0.sublayers?.forEach {
$0.removeFromSuperlayer()
}
}
}
public var nextState: TrafficLightState {
guard let index = states.index(where: { $0 === currentState }),
index + 1 < states.count else {
return states.first!
}
return states[index + 1]
}
}

2.定义state protocol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// MARK: - State Protocol
public protocol TrafficLightState: class {
// MARK: - Properties
var delay: TimeInterval { get }
// MARK: - Instance Methods
func apply(to context: TrafficLight)
}
extension TrafficLightState {
public func apply(to context: TrafficLight, after delay: TimeInterval) {
let queue = DispatchQueue.main
let dispatchTime = DispatchTime.now() + delay
queue.asyncAfter(deadline: dispatchTime) { [weak self, weak context] in
guard let self = self, let context = context else { return }
context.transition(to: self)
}
}
}

3.创建concrete states

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// MARK: - Concrete States
public class SolidTrafficLightState {
// MARK: - Properties
public let canisterIndex: Int
public let color: UIColor
public let delay: TimeInterval
// MARK: - Object Lifecycle
public init(canisterIndex: Int,
color: UIColor,
delay: TimeInterval) {
self.canisterIndex = canisterIndex
self.color = color
self.delay = delay
}
}
extension SolidTrafficLightState: TrafficLightState {
public func apply(to context: TrafficLight) {
let canisterLayer = context.canisterLayers[canisterIndex]
let circleShape = CAShapeLayer()
circleShape.path = canisterLayer.path!
circleShape.fillColor = color.cgColor
circleShape.strokeColor = color.cgColor
canisterLayer.addSublayer(circleShape)
}
}
extension SolidTrafficLightState {
public class func greenLight(
color: UIColor =
UIColor(red: 0.21, green: 0.78, blue: 0.35, alpha: 1),
canisterIndex: Int = 2,
delay: TimeInterval = 1.0) -> SolidTrafficLightState {
return SolidTrafficLightState(canisterIndex: canisterIndex,
color: color,
delay: delay)
}
public class func yellowLight(
color: UIColor =
UIColor(red: 0.98, green: 0.91, blue: 0.07, alpha: 1),
canisterIndex: Int = 1,
delay: TimeInterval = 0.5) -> SolidTrafficLightState {
return SolidTrafficLightState(canisterIndex: canisterIndex,
color: color,
delay: delay)
}
public class func redLight(
color: UIColor =
UIColor(red: 0.88, green: 0, blue: 0.04, alpha: 1),
canisterIndex: Int = 0,
delay: TimeInterval = 2.0) -> SolidTrafficLightState {
return SolidTrafficLightState(canisterIndex: canisterIndex,
color: color,
delay: delay)
}
}

4.使用状态模式

1
2
3
4
let greenYellowRed: [SolidTrafficLightState] =
[.greenLight(), .yellowLight(), .redLight()]
let trafficLight = TrafficLight(states: greenYellowRed)
PlaygroundPage.current.liveView = trafficLight

其他例子

  1. oc中的状态模式:https://juejin.im/post/5a3ca75551882515945ac5ff
  2. 售卖机例子:https://www.cnblogs.com/xiaofeixiang/p/5135479.html
  3. 在工程中试玩状态模式:https://www.cnblogs.com/R0SS/p/5408544.html

适配者模式

发表于 2019-11-26

适配者模式(Adapter Pattern)

适配者模式是一个行为模式,能够让不兼容的类型一起工作,它包含以下4个部分:

  1. object using an adapter:依赖new protocol的对象
  2. new protocol:使用所需的协议
  3. legacy object:在制定协议之前就已经存在,并且不能直接修改来遵循协议
  4. adapter:遵循协议,并将调用传递到legacy object上

新iPhone上没有耳机插口,如果你想把你的耳机插进新iPhone里,就需要一个适配者来连接彼此

什么时候应该使用适配者

类,模块和方法并不可能总是能够修改的,尤其是当他们来自第三方库时,所以有时你不得不适配它们。

你可以通过扩展一个存在的类或者新建一个类来创建一个适配者。

使用举例

在这个例子中,适配一个第三方授权服务和app内部的授权服务。

1.第三方类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Third-Party Classes
public class GoogleAuthenticator {
public func login(email: String,
password: String,
completion: @escaping (GoogleUser?, Error?) -> Void) {
// Make networking calls, which return a "Token"
let token = "special-token-value"
let user = GoogleUser(email: email, password: password, token: token)
completion(user, nil)
}
}
public struct GoogleUser {
public var email: String
public var password: String
public var token: String
}

2.授权协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// AuthenticationService
public protocol AuthenticationService {
func login(email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void)
}
public struct User {
public let email: String
public let password: String
}
public struct Token {
public let value: String
}

3.创建适配者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class GoogleAuthenticatorAdapter: AuthenticationService {
private var authenticator = GoogleAuthenticator()
public func login(email: String,
password: String,
success: @escaping (User, Token) -> Void,
failure: @escaping (Error?) -> Void) {
authenticator.login(email: email, password: password) { (googleUser, error) in
guard let googleUser = googleUser else {
failure(error)
return
}
let user = User(email: googleUser.email, password: googleUser.password)
let token = Token(value: googleUser.token)
success(user, token)
}
}
}

4.使用适配者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// MARK: - Example
var authService: AuthenticationService = GoogleAuthenticatorAdapter()
authService.login(
email: "user@example.com", password: "password",
success: { user, token in
print("Auth succeeded: \(user.email), \(token.value)")
}, failure: { error in
if let error = error {
print("Auth failed with error: \(error)")
} else {
print("Auth failed with error: no error given")
}
})

其他参考资料

  1. 视图类和模型类去耦合,使用适配者模式:https://www.jianshu.com/p/61ade7936c93
  2. 类适配器和对象适配器:https://www.jianshu.com/p/ef756fba5b74
12
蒋正义

蒋正义

18 日志
2 标签
© 2019 蒋正义
由 Hexo 强力驱动
主题 - NexT.Muse
访客数 人 总访问量 次