项目作者: flywo

项目描述 :
设计模式在Swift中的应用,使用的是Swift3.0。
高级语言: Swift
项目地址: git://github.com/flywo/SwiftDesignPattern.git


Swfit-DesignPattern

设计模式在Swift中的应用,使用的是Swift3.0。

实现:

  1. import Foundation
  2. import UIKit
  3. //定义了金钱的算法acceptcash,分别实现
  4. protocol CashBase {
  5. //所有计算都要遵循该协议,实现该方法
  6. func acceptCash(cash: CGFloat) -> CGFloat
  7. }
  8. //正常
  9. class CashNormal: CashBase {
  10. func acceptCash(cash: CGFloat) -> CGFloat {
  11. return cash
  12. }
  13. }
  14. //打折
  15. class CashRobate: CashBase {
  16. var moneyRebate: CGFloat
  17. init(rebate: CGFloat) {
  18. moneyRebate = rebate
  19. }
  20. func acceptCash(cash: CGFloat) -> CGFloat {
  21. return moneyRebate * cash
  22. }
  23. }
  24. //减免
  25. class CashReturn: CashBase {
  26. var moneyReturn: CGFloat
  27. init(retur: CGFloat) {
  28. moneyReturn = retur
  29. }
  30. func acceptCash(cash: CGFloat) -> CGFloat {
  31. return cash - moneyReturn
  32. }
  33. }
  34. enum CashType {
  35. case Normal
  36. case Robate
  37. case Return
  38. }
  39. class CashContext {
  40. var cashBase: CashBase
  41. init(type: CashType) {
  42. switch type {
  43. case .Normal:
  44. cashBase = CashNormal()
  45. case .Robate:
  46. cashBase = CashRobate(rebate: 0.5)
  47. case .Return:
  48. cashBase = CashReturn(retur: 10)
  49. }
  50. }
  51. func getResult(money: CGFloat) -> CGFloat {
  52. return cashBase.acceptCash(cash: money)
  53. }
  54. }

使用:

  1. //使用不同的算法,获得不同的结果
  2. let context = CashContext(type: .Normal)
  3. print("Normal结果:\(context.getResult(money: 100))")//Normal结果:100
  4. let retur = CashContext(type: .Return)
  5. print("Retrun结果:\(retur.getResult(money: 100))")//Retrun结果:90
  6. let robate = CashContext(type: .Robate)
  7. print("Robate结果:\(robate.getResult(money: 100))")//Robate结果:50

回到顶部

2.装饰模式


装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

实现:

  1. import Foundation
  2. protocol Phone {
  3. func call() -> String
  4. func video() -> String
  5. }
  6. class iPhone: Phone {
  7. func call() -> String {
  8. return "苹果打电话"
  9. }
  10. func video() -> String {
  11. return "苹果看电影"
  12. }
  13. }
  14. //父装饰器
  15. class PhoneDecorator: Phone {
  16. var phone: Phone
  17. init(phone: Phone) {
  18. self.phone = phone
  19. }
  20. func call() -> String {
  21. return phone.call()
  22. }
  23. func video() -> String {
  24. return phone.video()
  25. }
  26. }
  27. //增加流量功能
  28. final class PhoneDecoratorNet: PhoneDecorator {
  29. override func call() -> String {
  30. return "流量-\(phone.call())"
  31. }
  32. override func video() -> String {
  33. return "流量-\(phone.video())"
  34. }
  35. }
  36. //增加wifi功能
  37. class PhoneDecoratorWifi: PhoneDecorator {
  38. override func call() -> String {
  39. return "WIFI-\(phone.call())"
  40. }
  41. override func video() -> String {
  42. return "WIFI-\(phone.video())"
  43. }
  44. }

使用:

  1. let phone = iPhone()
  2. //装饰器增加了功能
  3. var decorator = PhoneDecorator(phone: phone)
  4. print(decorator.call())//苹果打电话
  5. print(decorator.video())//苹果看电影
  6. decorator = PhoneDecoratorNet(phone: phone)
  7. print(decorator.call())//流量-苹果打电话
  8. print(decorator.video())//流量-苹果看电影
  9. decorator = PhoneDecoratorWifi(phone: phone)
  10. print(decorator.call())//WIFI-苹果打电话
  11. print(decorator.video())//WIFI-苹果看电影

回到顶部

3.代理模式


代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。

实现:

  1. import Foundation
  2. //虚拟代理
  3. protocol Action {
  4. func run()
  5. func cry()
  6. }
  7. class Children: Action {
  8. func run() {
  9. print("孩子跑了")
  10. }
  11. func cry() {
  12. print("孩子哭了")
  13. }
  14. }
  15. class Youth: Action {
  16. lazy private var children: Children = Children()
  17. func run() {
  18. children.run()
  19. }
  20. func cry() {
  21. children.cry()
  22. }
  23. }
  24. //保护代理
  25. protocol Door {
  26. func open()
  27. }
  28. class Child: Door {
  29. func open() {
  30. print("好的,马上来开门!")
  31. }
  32. }
  33. class Parent: Door {
  34. private var child: Child!
  35. func haveChild(have: Bool) {
  36. guard have else {
  37. return
  38. }
  39. child = Child()
  40. }
  41. func open() {
  42. guard child != nil else {
  43. print("没有孩子,我自己来开门")
  44. return
  45. }
  46. child.open()
  47. }
  48. }

使用

  1. //虚拟代理,youth控制了child的行为
  2. let virtual = Youth()
  3. virtual.run()//孩子跑了
  4. virtual.cry()//孩子哭了
  5. //保护代理,对于控制孩子开门这个行为,增加了一个保护,如果没有孩子这个实例,则自己去开门
  6. let parent = Parent()
  7. parent.open()//没有孩子,我自己来开门
  8. parent.haveChild(have: true)
  9. parent.open()//好的,马上来开门

回到顶部

4.工厂方法模式


工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

实现:

  1. import Foundation
  2. //定义一个总的工厂类,让其子类决定创建出什么样的对象
  3. class Factory {
  4. func createProduct() -> String {
  5. return "电视"
  6. }
  7. }
  8. //长虹子类决定只创建长虹电视
  9. class ChangHoneFactory: Factory {
  10. override func createProduct() -> String {
  11. return "长虹电视"
  12. }
  13. }
  14. //海尔子类只创建海尔电视
  15. class HaierFactory: Factory {
  16. override func createProduct() -> String {
  17. return "海尔电视"
  18. }
  19. }

使用:

  1. //不同的工厂子类决定了要生成的实例
  2. var factory: Factory = ChangHoneFactory()
  3. print("创建出了:\(factory.createProduct())")//创建出了:长虹电视
  4. factory = HaierFactory()
  5. print("创建出了:\(factory.createProduct())")//创建出了:海尔电视

回到顶部

5.原型模式


原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

实现:

  1. //定义了一个程序员原型,假设有一大群程序员,他们之间的区别就是姓名不同,其余都相同
  2. class Programmer {
  3. var name: String?
  4. var age: Int
  5. var sex: String
  6. var language: String
  7. init(age: Int, sex: String, language: String) {
  8. self.language = language
  9. self.age = age
  10. self.sex = sex
  11. }
  12. //可以克隆自己
  13. func clone() -> Programmer {
  14. return Programmer(age: age, sex: sex, language: language)
  15. }
  16. }

使用:

  1. //从打印结果可以得出,韩梅梅我们只要克隆李雷,然后修改他的名字就可以了,无需重新创建
  2. let a = Programmer(age: 18, sex: "M", language: "swift")
  3. a.name = "李雷"
  4. print(dump(a))
  5. /*
  6. ▿ Prototype.Programmer #0
  7. ▿ name: Optional("李雷")
  8. - some: "李雷"
  9. - age: 18
  10. - sex: "M"
  11. - language: "swift"
  12. Prototype.Programmer
  13. */
  14. let b = a.clone()
  15. b.name = "韩梅梅"
  16. print(dump(b))
  17. /*
  18. ▿ Prototype.Programmer #0
  19. ▿ name: Optional("韩梅梅")
  20. - some: "韩梅梅"
  21. - age: 18
  22. - sex: "M"
  23. - language: "swift"
  24. Prototype.Programmer
  25. */

回到顶部

6.模板方法模式


模板方法模式(Template Method),定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

定义:

  1. import Foundation
  2. //定义了一套问题模板
  3. class Question {
  4. final func question() {
  5. print("如果有一天,不写程序了,你会去做什么?")
  6. print("我会去:\(answer())")
  7. }
  8. //默认是养猪
  9. func answer() -> String {
  10. return "养猪"
  11. }
  12. }
  13. //子类修改answer方法来修改结果
  14. class PersonA: Question {
  15. override func answer() -> String {
  16. return "下海经商"
  17. }
  18. }
  19. class PersonB: Question {
  20. override func answer() -> String {
  21. return "自己开公司"
  22. }
  23. }

使用:

  1. let s = Question()
  2. s.question()
  3. //如果有一天,不写程序了,你会去做什么?
  4. //我会去:养猪
  5. let a = PersonA()
  6. a.question()
  7. //如果有一天,不写程序了,你会去做什么?
  8. //我会去:下海经商
  9. let b = PersonB()
  10. b.question()
  11. //如果有一天,不写程序了,你会去做什么?
  12. //我会去:自己开公司

回到顶部

7.外观模式


外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

定义:

  1. import Foundation
  2. class Robot {
  3. //只需要调用该接口即可,内部的子系统无需使用者依次调用
  4. static func creatRobot() {
  5. Head.createHead()
  6. Body.createBody()
  7. Arm.createArm()
  8. Leg.createLeg()
  9. }
  10. }
  11. class Head {
  12. static func createHead() {
  13. print("制造头")
  14. }
  15. }
  16. class Body {
  17. static func createBody() {
  18. print("制造身体")
  19. }
  20. }
  21. class Arm {
  22. static func createArm() {
  23. print("制造手臂")
  24. }
  25. }
  26. class Leg {
  27. static func createLeg() {
  28. print("制造腿")
  29. }
  30. }

使用:

  1. Robot.creatRobot()
  2. /*
  3. 制造头
  4. 制造身体
  5. 制造手臂
  6. 制造腿
  7. */

回到顶部

8.建造者模式


建造者模式(Builder),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

实现:

  1. //创建对象需要的表示,需要用户自己定制
  2. struct LabelBuilder {
  3. var text: String
  4. var color: UIColor
  5. var rect: CGRect
  6. }
  7. class LabelDirector {
  8. //对象的构建,需要传入表示
  9. static func creatLableWithBuilder(builder: LabelBuilder) -> UILabel {
  10. let label = UILabel(frame: builder.rect)
  11. label.text = builder.text
  12. label.textColor = builder.color
  13. label.font = UIFont.systemFont(ofSize: 20)
  14. label.textAlignment = .center
  15. return label
  16. }
  17. }

使用:

  1. let builder = LabelBuilder(text: "按钮", color: .orange, rect: CGRect(x: 100, y: 100, width: view.frame.width-200, height: 30))
  2. //通过自定义标签的表示,用同一个构造方法构建标签
  3. let label = LabelDirector.creatLableWithBuilder(builder: builder)
  4. view.addSubview(label)

回到顶部

9.观察者模式


观察者模式(Observer),定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

实现:

  1. import Foundation
  2. enum NoticeType {
  3. case Lev1 //老板到公司门口了
  4. case Lev2 //老板进来办公室了
  5. }
  6. protocol ObserverProtocol {
  7. //定义了一个协议,实现
  8. func notice(type: NoticeType)
  9. }
  10. //公司前台小妹
  11. final class Reception {
  12. var observers: [ObserverProtocol]?
  13. func noticeLev1() {
  14. noticeEveryOne(lev: .Lev1)
  15. }
  16. func noticeLev2() {
  17. noticeEveryOne(lev: .Lev2)
  18. }
  19. private func noticeEveryOne(lev: NoticeType) {
  20. for obj in observers! {
  21. obj.notice(type: lev)
  22. }
  23. }
  24. }
  25. //好员工
  26. class Staff: ObserverProtocol {
  27. func notice(type: NoticeType) {
  28. print("员工\(String(describing: self))说:老板来了就来了呗,一直在专心工作")
  29. }
  30. }
  31. //员工a
  32. final class StaffA: Staff {
  33. override func notice(type: NoticeType) {
  34. switch type {
  35. case .Lev1:
  36. print("员工\(String(describing: self))说:不怕,继续看动画。")
  37. default:
  38. print("员工\(String(describing: self))说:不怕,我是老板侄儿,他不会骂我的。")
  39. }
  40. }
  41. }
  42. //员工B
  43. final class StaffB: Staff {
  44. override func notice(type: NoticeType) {
  45. switch type {
  46. case .Lev1:
  47. print("员工\(String(describing: self))说:赶紧关了,打开Xcode。")
  48. default:
  49. print("员工\(String(describing: self))说:恩,这破电脑,现在才打开Xcode,还好老板一进来已经打开了。")
  50. }
  51. }
  52. }

使用:

  1. let staff1 = Staff()
  2. let staff2 = StaffA()
  3. let staff3 = StaffB()
  4. let reception = Reception()
  5. reception.observers = [staff1, staff2, staff3]
  6. //公司员工123都关注前台小妹的通知,当老板快要进办公室时,小妹会通知所有人
  7. reception.noticeLev1()//老板到公司门口了,小妹发通知
  8. /*
  9. 员工Observer.Staff说:老板来了就来了呗,一直在专心工作
  10. 员工Observer.StaffA说:不怕,继续看动画。
  11. 员工Observer.StaffB说:赶紧关了,打开Xcode。
  12. */
  13. reception.noticeLev2()//老板进办公室了,小妹发通知
  14. /*
  15. 员工Observer.Staff说:老板来了就来了呗,一直在专心工作
  16. 员工Observer.StaffA说:不怕,我是老板侄儿,他不会骂我的。
  17. 员工Observer.StaffB说:恩,这破电脑,现在才打开Xcode,还好老板一进来已经打开了。
  18. */

回到顶部

10.抽象工厂模式


抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

实现:

  1. import Foundation
  2. //产品
  3. protocol ProductProtocol {
  4. var factory: String { get set }
  5. func showYouself()
  6. }
  7. struct Television: ProductProtocol {
  8. var factory: String
  9. func showYouself() {
  10. print("\(factory)生产的电视")
  11. }
  12. }
  13. struct Refrigerator: ProductProtocol {
  14. var factory: String
  15. func showYouself() {
  16. print("\(factory)生产的冰箱")
  17. }
  18. }
  19. //工厂
  20. enum ProductType {
  21. case Television, Refrigerator
  22. }
  23. class Factory {
  24. static func createProduct(type: ProductType) -> ProductProtocol {
  25. switch type {
  26. case .Television:
  27. return Television(factory: "工厂")
  28. default:
  29. return Refrigerator(factory: "工厂")
  30. }
  31. }
  32. }

使用:

  1. //工厂类提供了生产所有产品的接口,使用者无需知道要生产的具体类,只需要告诉工厂要的产品类型即可
  2. let tv = Factory.createProduct(type: .Television)
  3. let bx = Factory.createProduct(type: .Refrigerator)
  4. tv.showYouself()//工厂生产的电视
  5. bx.showYouself()//工厂生产的冰箱

回到顶部

11.状态模式


状态模式(State),当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。

实现:

  1. import Foundation
  2. enum MoodState {
  3. case happy, sad, normal
  4. }
  5. //状态
  6. struct State {
  7. var mood: MoodState
  8. }
  9. //一个程序员
  10. class Programmer {
  11. var state: State
  12. init(state: State) {
  13. self.state = state
  14. }
  15. func programming() {
  16. switch state.mood {
  17. case .happy:
  18. print("心情不错,开开心心的写程序")
  19. case .sad:
  20. print("心情糟糕,不想写程序")
  21. case .normal:
  22. print("心情正常,慢慢悠悠的写程序")
  23. }
  24. }
  25. }

使用:

  1. //修改programmer的state状态,即修改了programmer的programming()的行为
  2. let happy = State(mood: .happy)
  3. let programmer = Programmer(state: happy)
  4. programmer.programming()//心情不错,开开心心的写程序
  5. let sad = State(mood: .sad)
  6. programmer.state = sad
  7. programmer.programming()//心情糟糕,不想写程序
  8. let normal = State(mood: .normal)
  9. programmer.state = normal
  10. programmer.programming()//心情正常,慢慢悠悠的写程序

回到顶部

12.适配器模式


适配器模式(Adapter),将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

定义:

  1. //假如说游戏a中,asdw按钮分别代表游戏角色 左 下 右 上 移动,但是在游戏b中,asdw分别代表 左 蹲下 跳跃 右 的动作,此时,适配器模式就体现出用途了,游戏b写一个适配器即可使用asdw按键
  2. //游戏协议,分别定义出asdw四个键按下后需要实现的方法
  3. protocol AdapterProtocol {
  4. func a()
  5. func s()
  6. func d()
  7. func w()
  8. }
  9. //游戏对应的适配器
  10. class AdapterGameA: AdapterProtocol {
  11. var game: GameA
  12. init(game: GameA) {
  13. self.game = game
  14. }
  15. func a() {
  16. game.left()
  17. }
  18. func s() {
  19. game.down()
  20. }
  21. func d() {
  22. game.right()
  23. }
  24. func w() {
  25. game.up()
  26. }
  27. }
  28. class AdapterGameB: AdapterProtocol {
  29. var game: GameB
  30. init(game: GameB) {
  31. self.game = game
  32. }
  33. func a() {
  34. game.left()
  35. }
  36. func s() {
  37. game.squat()
  38. }
  39. func d() {
  40. game.right()
  41. }
  42. func w() {
  43. game.jump()
  44. }
  45. }
  46. //两款游戏
  47. class GameA {
  48. func left() {
  49. print("\(String(describing: self))左移动游戏角色")
  50. }
  51. func down() {
  52. print("\(String(describing: self))下移动游戏角色")
  53. }
  54. func right() {
  55. print("\(String(describing: self))右移动游戏角色")
  56. }
  57. func up() {
  58. print("\(String(describing: self))上移动游戏角色")
  59. }
  60. }
  61. class GameB {
  62. func left() {
  63. print("\(String(describing: self))左移动游戏角色")
  64. }
  65. func squat() {
  66. print("\(String(describing: self))蹲下游戏角色")
  67. }
  68. func right() {
  69. print("\(String(describing: self))右移动游戏角色")
  70. }
  71. func jump() {
  72. print("\(String(describing: self))跳起游戏角色")
  73. }
  74. }

使用:

  1. //定义出游戏ab,分别指定适配器
  2. let gameA = GameA()
  3. let gameB = GameB()
  4. let adapterA = AdapterGameA(game: gameA)
  5. let adapterB = AdapterGameB(game: gameB)
  6. //游戏开始了,分别按下asdw按键
  7. adapterA.a()//Adapter.GameA左移动游戏角色
  8. adapterA.s()//Adapter.GameA下移动游戏角色
  9. adapterA.d()//Adapter.GameA右移动游戏角色
  10. adapterA.w()//Adapter.GameA上移动游戏角色
  11. adapterB.a()//Adapter.GameB左移动游戏角色
  12. adapterB.s()//Adapter.GameB蹲下游戏角色
  13. adapterB.d()//Adapter.GameB右移动游戏角色
  14. adapterB.w()//Adapter.GameB跳起游戏角色

回到顶部

13.备忘录模式


备忘录模式(Memento),在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

定义:

  1. import Foundation
  2. //假设一款游戏里,一个角色有生命,蓝量两个状态,当用户要打boss前,可以先备份一下,打之前状态,发现打不过时,可以重新开始,从头打BOSS
  3. struct RollState {
  4. var life: Int
  5. var blue: Int
  6. }
  7. class Roll {
  8. var state: RollState
  9. init(state: RollState) {
  10. self.state = state
  11. }
  12. func saveState() -> RollState {
  13. return state
  14. }
  15. func restoreState(state: RollState) {
  16. self.state = state
  17. }
  18. func kill() {
  19. state.life = 0
  20. state.blue = 0
  21. }
  22. }

使用:

  1. let state = RollState(life: 100, blue: 100)//初始化角色
  2. let roll = Roll(state: state)
  3. let mementoState = roll.saveState()
  4. print(dump(roll))
  5. /*打印角色初始状态
  6. ▿ Memento.Roll #0
  7. ▿ state: Memento.RollState
  8. - life: 100
  9. - blue: 100
  10. Memento.Roll
  11. */
  12. roll.kill()
  13. print(dump(roll))
  14. /*角色死亡状态
  15. ▿ Memento.Roll #0
  16. ▿ state: Memento.RollState
  17. - life: 0
  18. - blue: 0
  19. Memento.Roll
  20. */
  21. roll.restoreState(state: mementoState)
  22. print(dump(roll))
  23. /*角色恢复后状态
  24. ▿ Memento.Roll #0
  25. ▿ state: Memento.RollState
  26. - life: 100
  27. - blue: 100
  28. Memento.Roll
  29. */

回到顶部

14.组合模式


组合模式(Composite),将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

定义:

  1. import Foundation
  2. //画图案的协议
  3. protocol DrawProtocol {
  4. func draw()
  5. }
  6. class Circle: DrawProtocol {
  7. func draw() {
  8. print("我负责画圆")
  9. }
  10. }
  11. class Square: DrawProtocol {
  12. func draw() {
  13. print("我负责画方形")
  14. }
  15. }
  16. class Triangle: DrawProtocol {
  17. func draw() {
  18. print("我负责画三角形")
  19. }
  20. }
  21. class Print: DrawProtocol {
  22. var drawer = [DrawProtocol]()
  23. func addDrawer(_ drawer: DrawProtocol...) {
  24. self.drawer.append(contentsOf: drawer)
  25. }
  26. func draw() {
  27. _ = drawer.map{$0.draw()}
  28. }
  29. }

使用:

  1. //单个对象可以单独使用draw函数,也可以组合到一起,使用组合后的draw
  2. let a = Circle()
  3. let b = Square()
  4. let c = Triangle()
  5. a.draw()//我负责画圆
  6. b.draw()//我负责画方形
  7. c.draw()//我负责画三角形
  8. let p = Print()
  9. p.addDrawer(a,b,c)
  10. p.draw()
  11. /*
  12. 我负责画圆
  13. 我负责画方形
  14. 我负责画三角形
  15. */

回到顶部

15.迭代器模式


迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

定义:

  1. import Foundation
  2. //定义了一个算法,利用迭代器后,会依次输出结果
  3. struct Algorithm {
  4. var index: Int
  5. }
  6. //定义了该算法的迭代器
  7. struct AlgorithmIterator: IteratorProtocol {
  8. private var current = 1
  9. var begin: Int
  10. init(begin: Int) {
  11. self.begin = begin
  12. }
  13. mutating func next() -> Algorithm? {
  14. defer {
  15. current += 1
  16. }
  17. return Algorithm(index: current * begin)
  18. }
  19. }
  20. //扩展了该算法,增加一个迭代器方法
  21. extension Algorithm: Sequence {
  22. func makeIterator() -> AlgorithmIterator {
  23. return AlgorithmIterator(begin: index)
  24. }
  25. }

使用:

  1. let algorithm = Algorithm(index: 10)
  2. var iterator = algorithm.makeIterator()
  3. for _ in 1...10 {
  4. print((iterator.next()?.index)!)
  5. }
  6. /*打印结果:
  7. 10
  8. 20
  9. 30
  10. 40
  11. 50
  12. 60
  13. 70
  14. 80
  15. 90
  16. 100
  17. */

回到顶部

16.单例模式


单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点。

定义:

  1. import Foundation
  2. class Singleton {
  3. var index = 0
  4. static let share = Singleton()
  5. private init() {}
  6. }

使用:

  1. //single是单例
  2. let single = Singleton.share
  3. print(single.index)//0
  4. single.index = 100
  5. print(single.index)//100
  6. //无论获取多少次,都是同一个实例
  7. print(Singleton.share.index)//100

回到顶部

17.桥接模式


桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。

定义:

  1. import Foundation
  2. //接口协议
  3. protocol InterfaceProtocol {
  4. var app: RealizeProtocol {get set}
  5. func open()
  6. }
  7. //实现协议
  8. protocol RealizeProtocol {
  9. func appOpen()
  10. }
  11. //操作类
  12. class Control: InterfaceProtocol {
  13. var app: RealizeProtocol
  14. init(app: RealizeProtocol) {
  15. self.app = app
  16. }
  17. func open() {
  18. app.appOpen()
  19. }
  20. }
  21. //地图
  22. class Map: RealizeProtocol {
  23. func appOpen() {
  24. print("打开地图,开始定位!")
  25. }
  26. }
  27. //相机
  28. class Camera: RealizeProtocol {
  29. func appOpen() {
  30. print("打开摄像头,开始拍照!")
  31. }
  32. }

使用:

  1. let map = Map()
  2. let camera = Camera()
  3. //把对应app给控制类,运行控制类的抽象接口,则会运行app的接口实现
  4. let control = Control(app: map)
  5. control.open()//打开地图,开始定位!
  6. control.app = camera
  7. control.open()//打开摄像头,开始拍照!

回到顶部

18.命令模式


命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。

定义:

  1. import Foundation
  2. enum DoorActionType {
  3. case open, close, lock, unlock
  4. }
  5. //命令协议,命令需要实现execute方法
  6. protocol CommandProtocol {
  7. func execute()
  8. }
  9. //门
  10. struct Door {
  11. var name: String
  12. }
  13. //门可以执行的操作:开门,关门,上锁,解锁
  14. class DoorAction: CommandProtocol {
  15. var actionType: DoorActionType
  16. var door: Door
  17. init(type: DoorActionType ,door: Door) {
  18. actionType = type
  19. self.door = door
  20. }
  21. func execute() {
  22. switch actionType {
  23. case .open:
  24. print("\(door.name)执行开门命令!")
  25. case .close:
  26. print("\(door.name)执行关门命令!")
  27. case .lock:
  28. print("\(door.name)执行上锁命令!")
  29. case .unlock:
  30. print("\(door.name)执行解锁命令!")
  31. }
  32. }
  33. }
  34. //命令管理者
  35. class DoorManager {
  36. var actions = [CommandProtocol]()
  37. //添加命令
  38. func add(_ actions: CommandProtocol...) {
  39. self.actions += actions
  40. }
  41. //执行命令
  42. func execute() {
  43. _ = actions.map{$0.execute()}
  44. }
  45. }

使用:

  1. //实例化了一个门,定义了门的动作
  2. let door = Door(name: "客厅门")
  3. let open = DoorAction(type: .open, door: door)
  4. let close = DoorAction(type: .close, door: door)
  5. let lock = DoorAction(type: .lock, door: door)
  6. let unlock = DoorAction(type: .unlock, door: door)
  7. //实例化了门管理者
  8. let manager = DoorManager()
  9. //添加门的动作
  10. manager.add(open, close, lock, unlock)
  11. //执行添加了的命令
  12. manager.execute()
  13. /*
  14. 客厅门执行开门命令!
  15. 客厅门执行关门命令!
  16. 客厅门执行上锁命令!
  17. 客厅门执行解锁命令!
  18. */

回到顶部

19.职责链模式


职责链模式(Chain of Responsibility),使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

实现:

  1. import Foundation
  2. //问题协议
  3. protocol QuestionProtocol {
  4. //指定自己回答不出来,下一个回答的人
  5. var next: QuestionProtocol? {get set}
  6. //该方法用于问问题
  7. func answerQuestion(question: String)
  8. }
  9. struct Student: QuestionProtocol {
  10. var name: String
  11. var canAnswerQuestion: String
  12. var next: QuestionProtocol?
  13. func answerQuestion(question: String) {
  14. switch question {
  15. case canAnswerQuestion:
  16. print("\(name)回答:1+1=2")
  17. case canAnswerQuestion:
  18. print("\(name)回答:1*2=2")
  19. case canAnswerQuestion:
  20. print("\(name)回答:2*2=4")
  21. case canAnswerQuestion:
  22. print("\(name)回答:3*2=6")
  23. default:
  24. if let next = next {
  25. next.answerQuestion(question: question)
  26. }else {
  27. print("这个问题没人知道答案!")
  28. }
  29. }
  30. }
  31. }

使用:

  1. let stu1 = Student(name: "小明", canAnswerQuestion: "1+1", next: nil)
  2. let stu2 = Student(name: "小黄", canAnswerQuestion: "1*2", next: stu1)
  3. let stu3 = Student(name: "小芳", canAnswerQuestion: "2*2", next: stu2)
  4. let stu4 = Student(name: "小辉", canAnswerQuestion: "3*2", next: stu3)
  5. //从4开始,自动依次调用,直到有人回答或者都没人回答结束
  6. stu4.answerQuestion(question: "3*2")//小辉回答:1+1=2
  7. stu4.answerQuestion(question: "2*2")//小芳回答:1+1=2
  8. stu4.answerQuestion(question: "1*2")//小黄回答:1+1=2
  9. stu4.answerQuestion(question: "1+1")//小明回答:1+1=2
  10. stu4.answerQuestion(question: "3*3")//这个问题没人知道答案!

回到顶部

20.中介者模式


中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

实现:

  1. import Foundation
  2. //制造协议
  3. protocol CreateProtocol {
  4. var name: String {get set}
  5. func create() -> Any
  6. }
  7. //钢铁
  8. struct Steel {
  9. var name: String
  10. var createFrom: String
  11. }
  12. //机器人结构体
  13. struct Robot {
  14. var name: String
  15. var steel: Steel
  16. var createFrom: String
  17. }
  18. //优质造铁厂
  19. class SteelFactory: CreateProtocol {
  20. var name: String
  21. init(name: String) {
  22. self.name = name
  23. }
  24. func create() -> Any {
  25. return Steel(name: "优质钢材", createFrom: name)
  26. }
  27. }
  28. //劣质造铁厂
  29. class SteelFactoryLow: CreateProtocol {
  30. var name: String
  31. init(name: String) {
  32. self.name = name
  33. }
  34. func create() -> Any {
  35. return Steel(name: "劣质钢材", createFrom: name)
  36. }
  37. }
  38. //制造机器人的公司
  39. class RobotCompany: CreateProtocol {
  40. var mediator: Mediator
  41. var name: String
  42. init(mediator: Mediator, name: String) {
  43. self.name = name
  44. self.mediator = mediator
  45. }
  46. //机器人制造公司需要钢材,然后向中介者要钢材,中介者去向工厂要。中介者和工厂没有相互引用,工厂可以被替换。
  47. func create() -> Any {
  48. return Robot(name: "阿狸机器人", steel: mediator.needSteel(), createFrom: name)
  49. }
  50. }
  51. //中介者
  52. class Mediator {
  53. var steelFactory: CreateProtocol
  54. init(stellFactory: SteelFactory) {
  55. self.steelFactory = stellFactory
  56. }
  57. //向中介者要钢材
  58. func needSteel() -> Steel {
  59. return steelFactory.create() as! Steel
  60. }
  61. }

使用:

  1. let factory = SteelFactory(name: "成都钢铁厂")
  2. let factoryLow = SteelFactoryLow(name: "劣质钢铁厂")
  3. let mediator = Mediator(stellFactory: factory)
  4. let company = RobotCompany(mediator: mediator, name: "成都机器人公司")
  5. //开始制造
  6. let robot = company.create() as! Robot
  7. print(robot.createFrom+"制造的机器人\(robot.name),采用的是"+robot.steel.createFrom+"生产的"+robot.steel.name+"!")//成都机器人公司制造的机器人阿狸机器人,采用的是成都钢铁厂生产的优质钢材!
  8. //中介者更换了钢铁厂,钢铁厂和机器人公司是没有引用的
  9. mediator.steelFactory = factoryLow
  10. let robot1 = company.create() as! Robot
  11. print(robot1.createFrom+"制造的机器人\(robot1.name),采用的是"+robot1.steel.createFrom+"生产的"+robot1.steel.name+"!")//成都机器人公司制造的机器人阿狸机器人,采用的是劣质钢铁厂生产的劣质钢材!

回到顶部

21.享元模式


享元模式(Flyweight),运用共享技术有效地支持大量细粒度的对象。

实现:

  1. import Foundation
  2. //假设有一家杂货店,一开始老板不知道卖什么,有人来买,马上就制造,进货后就会不会缺货,我们就可以使用享元模式,将有人买过的东西保存起来共享,再有人买直接拿出来就可以,不用再去进新的货。
  3. //商品
  4. struct Commodity: CustomStringConvertible {//CustomStringConvertible该协议能够使自定义输出实例的description
  5. var commodity: String
  6. var description: String {
  7. get {
  8. return "商品名称:"+commodity
  9. }
  10. }
  11. }
  12. //杂货店
  13. class GroceryStore {
  14. //商品列表
  15. private var list = [String: Commodity]()
  16. //mutating关键字作用:在方法中修改struct和enum变量,如果不加,会提示无法修改结构体成员
  17. func buyCommodity(name: String) -> Commodity {
  18. //无货,制造,制造好后,放到list中共享
  19. if !list.keys.contains(name) {
  20. print("没有这个货,给你制造!")
  21. list[name] = Commodity(commodity: name)
  22. }else {
  23. print("有货,直接给你拿!")
  24. }
  25. return list[name]!
  26. }
  27. }

使用:

  1. let shop = GroceryStore()
  2. let commodity1 = shop.buyCommodity(name: "电视")//没有电视,会去创建新的对象
  3. print(commodity1)
  4. /*
  5. 没有这个货,给你制造!
  6. 商品名称:电视
  7. */
  8. let commodity2 = shop.buyCommodity(name: "电视")//已经有电视了,去共享的list中取
  9. print(commodity2)
  10. /*
  11. 有货,直接给你拿!
  12. 商品名称:电视
  13. */

回到顶部

22.解释器模式


解释器模式(Interpreter),给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

实现:

  1. import Foundation
  2. //定义一种新的语法,用字符表示,解释"1+2"这个字符串的含义
  3. protocol Interpreter {
  4. //返回一个泛型Result
  5. static func interpreter<Result>(input: String) -> Result
  6. }
  7. //整型解释器
  8. struct IntInterpreter: Interpreter {
  9. internal static func interpreter<Result>(input: String) -> Result {
  10. let arr = input.components(separatedBy: "+")
  11. return (Int(arr.first!)! + Int(arr.last!)!) as! Result
  12. }
  13. }
  14. //字符解析器
  15. struct StringInterpreter: Interpreter {
  16. internal static func interpreter<Result>(input: String) -> Result {
  17. let arr = input.components(separatedBy: "+")
  18. return (arr.first! + arr.last!) as! Result
  19. }
  20. }

使用:

  1. let result: Int = IntInterpreter.interpreter(input: "14+14")
  2. print(result)//28
  3. let result2: String = StringInterpreter.interpreter(input: "14+14")
  4. print(result2)//1414

回到顶部

23.访问者模式


访问者模式(Visitor),表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

实现:

  1. import Foundation
  2. //假设一个人要去访问朋友ABCD
  3. //访客协议
  4. protocol VisitorProtocol {
  5. func visit(planet: FriendA)
  6. func visit(planet: FriendB)
  7. func visit(planet: FriendC)
  8. func visit(planet: FriendD)
  9. }
  10. //朋友的协议
  11. protocol FriendProtocol {
  12. func accept(vistor: VisitorProtocol)
  13. }
  14. //A
  15. class FriendA: FriendProtocol {
  16. func accept(vistor: VisitorProtocol) {
  17. vistor.visit(planet: self)
  18. }
  19. }
  20. //B
  21. class FriendB: FriendProtocol {
  22. func accept(vistor: VisitorProtocol) {
  23. vistor.visit(planet: self)
  24. }
  25. }
  26. //C
  27. class FriendC: FriendProtocol {
  28. func accept(vistor: VisitorProtocol) {
  29. vistor.visit(planet: self)
  30. }
  31. }
  32. //D
  33. class FriendD: FriendProtocol {
  34. func accept(vistor: VisitorProtocol) {
  35. vistor.visit(planet: self)
  36. }
  37. }
  38. //访客
  39. class Visitor: VisitorProtocol {
  40. var address = ""
  41. func visit(planet: FriendA) {
  42. address = "访问了朋友A"
  43. }
  44. func visit(planet: FriendB) {
  45. address = "访问了朋友B"
  46. }
  47. func visit(planet: FriendC) {
  48. address = "访问了朋友C"
  49. }
  50. func visit(planet: FriendD) {
  51. address = "访问了朋友D"
  52. }
  53. }

使用:

  1. //分别创建出朋友
  2. let friends: [FriendProtocol] = [FriendA(), FriendB(), FriendC(), FriendD()]
  3. //每个朋友都去访问
  4. let visitors = friends.map{ (friend: FriendProtocol) -> Visitor in
  5. let visitor = Visitor()
  6. //访问过后,自己的数据就变了
  7. friend.accept(vistor: visitor)
  8. return visitor
  9. }
  10. print(dump(visitors))
  11. /*
  12. ▿ 4 elements
  13. ▿ Visitor.Visitor #0
  14. - address: "访问了朋友A"
  15. ▿ Visitor.Visitor #1
  16. - address: "访问了朋友B"
  17. ▿ Visitor.Visitor #2
  18. - address: "访问了朋友C"
  19. ▿ Visitor.Visitor #3
  20. - address: "访问了朋友D"
  21. [Visitor.Visitor, Visitor.Visitor, Visitor.Visitor, Visitor.Visitor]
  22. */

回到顶部