├── README.md ├── 代理模式-Proxy Pattern ├── 代码 │ ├── 虚拟代理.swift │ └── 远程代理与保护代理.swift ├── 截图 │ ├── 屏幕快照 2016-05-03 下午1.21.29.png │ ├── 屏幕快照 2016-05-03 下午1.22.50.png │ ├── 屏幕快照 2016-05-03 下午1.24.26.png │ ├── 屏幕快照 2016-05-03 下午1.27.13.png │ ├── 屏幕快照 2016-05-03 下午1.27.41.png │ ├── 屏幕快照 2016-05-03 下午1.40.26.png │ └── 屏幕快照 2016-05-03 下午1.52.16.png └── 类图 │ └── C7481877-EC1E-44FA-90A6-7DEC520C803C.png ├── 单例模式-Singleton Pattern └── Singleton.swift ├── 命令模式-Command Pattern ├── Command.png └── Command.swift ├── 外观模式-Facade Pattern ├── 代码 │ ├── 外观模式.swift │ └── 无“外观模式”.swift └── 类图 │ ├── 外观模式.png │ └── 无外观模式.png ├── 工厂模式-Factory Pattern ├── 示例代码 │ ├── 工厂方法模式.swift │ ├── 抽象工厂+工厂方法模式.swift │ ├── 抽象工厂模式.swift │ ├── 无工厂模式.swift │ └── 简单工厂模式.swift └── 类图 │ ├── 工厂方法模式.png │ ├── 抽象工厂+工厂方法模式.png │ ├── 抽象工厂模式.png │ ├── 无工厂模式.png │ └── 简单工厂模式.png ├── 模板方法模式-Template Method Pattern ├── 代码 │ ├── 无模板方法.swift │ └── 有模板方法.swift └── 类图.png ├── 状态模式-State Pattern ├── 代码 │ ├── 无“状态模式”ATM.swift │ └── 有“状态模式”ATM.swift └── 类图 │ ├── 屏幕快照 2016-04-28 下午4.13.33.png │ └── 屏幕快照 2016-04-28 下午5.01.38.png ├── 策略模式-Strategy Pattern ├── 01.png ├── 02.png ├── 03.png ├── Duck1.swift ├── Duck2.swift └── StrategyPattern.swift ├── 组合模式-Composite Pattern ├── 代码 │ └── File.swift └── 类图 │ └── E7554EE6-D9AA-4F3A-B85D-EFF7637C9256.png ├── 装饰者模式-Decorator Pattern ├── 代码 │ ├── Coffee.swift │ └── Flower.swift └── 类图 │ ├── CFAD9C6B-41C1-4A4E-BFB0-B5CA4D300959.png │ ├── 屏幕快照 2016-04-05 下午4.16.50.png │ └── 屏幕快照 2016-04-05 下午5.16.17.png ├── 观察者模式-Observer Pattern ├── BCF7A2A0-0384-44E6-9411-0E9275132BAA.png ├── MyCustomNotificationCenter.swift ├── Notification.swift ├── ObserverAndSubject.swift ├── 屏幕快照 2016-03-23 上午10.25.34.png └── 屏幕快照 2016-03-23 下午3.26.31.png ├── 迭代器模式-Iterator Pattern ├── 代码 │ ├── 无“迭代器模式”.swift │ └── 迭代器模式.swift └── 类图 │ ├── 工厂方法+迭代器.png │ └── 无迭代器.png └── 适配器模式-Adapter Pattern ├── 代码 ├── 电源适配器.swift └── Demo1.swift └── 适配器类图.png /README.md: -------------------------------------------------------------------------------- 1 | # DesignPatterns-Swift 2 | 使用Swift实现的常用设计模式示例 3 | -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/代码/虚拟代理.swift: -------------------------------------------------------------------------------- 1 | //代理模式:为另一个对象提供一个替身或占位符以控制对这个对象的访问。 2 | //远程代理:控制访问远程对象 3 | //保护代理:基于权限的资源访问 4 | //虚拟代理:控制访问创建开销大的资源 5 | 6 | 7 | //===虚拟代理======= 8 | //给大对象创建替身,以图片的占位图为例 9 | 10 | protocol ImageType { 11 | func imageLoad() 12 | } 13 | 14 | 15 | class BigImage: ImageType { 16 | func imageLoad() { 17 | print("大图片") 18 | } 19 | } 20 | 21 | class SmallImage: ImageType { 22 | func imageLoad() { 23 | print("小占位图片") 24 | } 25 | } 26 | 27 | 28 | //图片虚拟代理 29 | class BigImageProxy: ImageType { 30 | var bigImage: ImageType? = nil 31 | var bigImageNoInit: Bool = true 32 | var smallImage: ImageType = SmallImage() 33 | 34 | func imageLoad() { 35 | if bigImage != nil { 36 | bigImage?.imageLoad() 37 | } else { 38 | smallImage.imageLoad() 39 | 40 | if bigImageNoInit { 41 | self.bigImage = BigImage() //模拟长时间的初始化 42 | bigImageNoInit = false 43 | } 44 | 45 | } 46 | } 47 | } 48 | 49 | class ImageClient { 50 | var image: ImageType? 51 | 52 | func setImage(image: ImageType) -> Void { 53 | self.image = image 54 | } 55 | 56 | func imageLoad() { 57 | image?.imageLoad() 58 | } 59 | } 60 | 61 | let imageClient = ImageClient() 62 | imageClient.setImage(BigImageProxy()) 63 | imageClient.imageLoad() 64 | imageClient.imageLoad() 65 | 66 | -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/代码/远程代理与保护代理.swift: -------------------------------------------------------------------------------- 1 | //代理模式:为另一个对象提供一个替身或占位符以控制对这个对象的访问。 2 | //远程代理:控制访问远程对象 3 | //保护代理:基于权限的资源访问 4 | //虚拟代理:控制访问创建开销大的资源 5 | 6 | 7 | 8 | protocol InternetAccessProtocol { 9 | func response() 10 | func getId() -> String 11 | } 12 | 13 | class Facebook: InternetAccessProtocol { 14 | func response() { 15 | print("你好,欢迎访问脸书 ") 16 | } 17 | 18 | func getId() -> String { 19 | return "FaceBook" 20 | } 21 | } 22 | 23 | class Twitter: InternetAccessProtocol { 24 | func response() { 25 | print("你好,欢迎访问推特") 26 | } 27 | 28 | func getId() -> String { 29 | return "FaceBook" 30 | } 31 | } 32 | 33 | class Cnblogs: InternetAccessProtocol { 34 | func response() { 35 | print("你好,欢迎访问博客园") 36 | } 37 | 38 | func getId() -> String { 39 | return "Cnblogs" 40 | } 41 | } 42 | 43 | 44 | 45 | 46 | 47 | 48 | protocol ProxyType: InternetAccessProtocol { 49 | func setDelegate(delegate: InternetAccessProtocol) 50 | } 51 | 52 | 53 | //==========远程代理======== 54 | 55 | class ShadowsocksProxy: ProxyType { 56 | private var delegate: InternetAccessProtocol? = nil 57 | 58 | init(delegate: InternetAccessProtocol? = nil) { 59 | self.delegate = delegate 60 | } 61 | 62 | func setDelegate(delegate: InternetAccessProtocol) { 63 | self.delegate = delegate 64 | } 65 | 66 | func response() { 67 | delegate?.response() 68 | } 69 | 70 | func getId() -> String { 71 | return "ShadowsocksProxy" 72 | } 73 | } 74 | 75 | //=======保护代理============ 76 | class GreatFirewall: ProxyType { 77 | //黑名单 78 | private var blackList: Array = [Facebook().getId(), Twitter().getId()] 79 | 80 | private var delegate: InternetAccessProtocol? = nil 81 | 82 | func setDelegate(delegate: InternetAccessProtocol) { 83 | if hasInTheBlackList(delegate) { 84 | print("你访问的\(delegate.getId())不可用") 85 | self.delegate = nil 86 | } else { 87 | self.delegate = delegate 88 | } 89 | } 90 | 91 | func response() { 92 | delegate?.response() 93 | } 94 | 95 | func getId() -> String { 96 | return (delegate?.getId())! 97 | } 98 | 99 | //判断是否被墙 100 | func hasInTheBlackList(webSite: InternetAccessProtocol) -> Bool { 101 | return blackList.contains { (item) -> Bool in 102 | if webSite.getId() == item { 103 | return true 104 | } else { 105 | return false 106 | } 107 | } 108 | } 109 | } 110 | 111 | 112 | class Client { 113 | private var shadowsocksProxy: ProxyType = ShadowsocksProxy() 114 | private var greatFirewall: ProxyType = GreatFirewall() 115 | 116 | func useProxyAcccessWebSite(webSite: InternetAccessProtocol) { 117 | shadowsocksProxy.setDelegate(webSite) //为代理指定代理对象,也就是要访问的网站 118 | shadowsocksProxy.response() 119 | } 120 | 121 | func useGreatFirewall(webSite: InternetAccessProtocol) { 122 | greatFirewall.setDelegate(webSite) 123 | greatFirewall.response() 124 | } 125 | } 126 | 127 | let client = Client() 128 | 129 | print("使用远程代理直接访问Facebook:") 130 | client.useProxyAcccessWebSite(Facebook()) 131 | 132 | print("\n经过防火墙直接访问FaceBook:") 133 | client.useGreatFirewall(Facebook()) 134 | 135 | print("\n经过防火墙访问远程代理,然后使用远程代理来访问Facebook:") 136 | client.useGreatFirewall(ShadowsocksProxy(delegate: Facebook())) 137 | 138 | print("\n经过防火墙直接访问博客园:") 139 | client.useGreatFirewall(Cnblogs()) 140 | 141 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.21.29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.21.29.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.22.50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.22.50.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.24.26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.24.26.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.27.13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.27.13.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.27.41.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.27.41.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.40.26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.40.26.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.52.16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/截图/屏幕快照 2016-05-03 下午1.52.16.png -------------------------------------------------------------------------------- /代理模式-Proxy Pattern/类图/C7481877-EC1E-44FA-90A6-7DEC520C803C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/代理模式-Proxy Pattern/类图/C7481877-EC1E-44FA-90A6-7DEC520C803C.png -------------------------------------------------------------------------------- /单例模式-Singleton Pattern/Singleton.swift: -------------------------------------------------------------------------------- 1 | //---单例模式0(Singleton Pattern)--- 2 | //单例模式:确保一个类只有一个实例,并提供一个全局访问点。 3 | 4 | //使用GCD来创建单例 5 | class SingletonManager { 6 | static private var onceToken: dispatch_once_t = 0 7 | static private var staticInstance: SingletonManager? = nil 8 | static func sharedInstance() -> SingletonManager { 9 | dispatch_once(&onceToken) { 10 | staticInstance = SingletonManager() 11 | } 12 | return staticInstance! 13 | } 14 | private init() {} 15 | } 16 | 17 | let single1 = SingletonManager.sharedInstance() 18 | let single2 = SingletonManager.sharedInstance() 19 | unsafeAddressOf(single1) 20 | unsafeAddressOf(single2) 21 | 22 | 23 | 24 | //静态变量进行创建 25 | class SingletonManager1 { 26 | static private let staticInstance: SingletonManager1 = SingletonManager1() 27 | static func sharedInstance() -> SingletonManager1 { 28 | return staticInstance 29 | } 30 | private init() {} 31 | } 32 | 33 | let single01 = SingletonManager1.sharedInstance() 34 | let single02 = SingletonManager1.sharedInstance() 35 | 36 | unsafeAddressOf(single01) 37 | unsafeAddressOf(single02) -------------------------------------------------------------------------------- /命令模式-Command Pattern/Command.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/命令模式-Command Pattern/Command.png -------------------------------------------------------------------------------- /命令模式-Command Pattern/Command.swift: -------------------------------------------------------------------------------- 1 | //--命令模式: 将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。 2 | 3 | //外设 4 | class Light { 5 | func on() { 6 | print("电灯已打开") 7 | } 8 | 9 | func off() { 10 | print("电灯已关闭") 11 | } 12 | } 13 | 14 | class Computer { 15 | func start() { 16 | print("计算机正在启动") 17 | } 18 | 19 | func screenLight() { 20 | print("屏幕已经点亮") 21 | } 22 | 23 | func load() { 24 | print("计算机正在加载系统") 25 | } 26 | 27 | func startOver() { 28 | print("计算机启动完毕") 29 | } 30 | 31 | func off() { 32 | print("计算机已关闭") 33 | } 34 | } 35 | 36 | 37 | //命令 38 | protocol Command { 39 | func execute() -> Void 40 | } 41 | 42 | 43 | class LightOnCommand: Command { 44 | private let light = Light() 45 | func execute() { 46 | light.on() 47 | } 48 | } 49 | 50 | class LightOffCommand: Command { 51 | private let light = Light() 52 | func execute() { 53 | light.off() 54 | } 55 | } 56 | 57 | class ComputerStartCommand: Command { 58 | private let computer = Computer() 59 | func execute() { 60 | computer.start() 61 | computer.screenLight() 62 | computer.load() 63 | computer.startOver() 64 | } 65 | } 66 | 67 | //控制台 68 | class Console { 69 | private var command: Command? = nil 70 | 71 | func setCommand(command: Command) { 72 | self.command = command 73 | } 74 | 75 | func action() { 76 | command?.execute() 77 | } 78 | } 79 | 80 | 81 | 82 | var console: Console = Console() 83 | 84 | console.setCommand(LightOnCommand()) 85 | console.action() 86 | 87 | console.setCommand(LightOffCommand()) 88 | console.action() 89 | 90 | console.setCommand(ComputerStartCommand()) 91 | console.action() 92 | 93 | -------------------------------------------------------------------------------- /外观模式-Facade Pattern/代码/外观模式.swift: -------------------------------------------------------------------------------- 1 | //插排接口 2 | protocol SocketType { 3 | func on() -> Void 4 | func off() -> Void 5 | } 6 | //公牛插排 7 | class OXSocket: SocketType { 8 | func on() { 9 | print("公牛开关已打开") 10 | } 11 | 12 | func off() { 13 | print("公牛开关已关闭") 14 | } 15 | } 16 | 17 | //笔记本接口 18 | protocol ComputerType { 19 | func startUp() -> Void 20 | func shutdown() -> Void 21 | } 22 | 23 | //MacBookPro 24 | class MacBookPro: ComputerType { 25 | func startUp() { 26 | print("OS X 已启动") 27 | } 28 | 29 | func shutdown() { 30 | print("OS X 已关闭") 31 | } 32 | } 33 | 34 | 35 | //显示器接口 36 | protocol DisplayDeviceType { 37 | func on() -> Void 38 | func off() -> Void 39 | } 40 | 41 | //三星显示器 42 | class SamsungDisplay: DisplayDeviceType { 43 | func on() { 44 | print("三星显示器已打开") 45 | } 46 | 47 | func off() { 48 | print("三星显示器已关闭") 49 | } 50 | } 51 | 52 | 53 | //将上面的内容使用外观模式进行简化 54 | class EveryDayWorking { 55 | private var socket: SocketType = OXSocket() 56 | private var cumputer: ComputerType = MacBookPro() 57 | private var display: DisplayDeviceType = SamsungDisplay() 58 | 59 | func setSocket(socket: SocketType) { 60 | self.socket = socket 61 | } 62 | 63 | func setCumputer(cumputer: ComputerType) { 64 | self.cumputer = cumputer 65 | } 66 | 67 | func setDisplay(display: DisplayDeviceType) { 68 | self.display = display 69 | } 70 | 71 | func startWorking() { 72 | print("开始工作:") 73 | socket.on() 74 | cumputer.startUp() 75 | display.on() 76 | } 77 | 78 | func endWorking() { 79 | print("结束工作:") 80 | display.off() 81 | cumputer.shutdown() 82 | socket.off() 83 | } 84 | } 85 | 86 | 87 | 88 | let everyDayWorking = EveryDayWorking() 89 | everyDayWorking.startWorking() 90 | print("\n") 91 | everyDayWorking.endWorking() 92 | -------------------------------------------------------------------------------- /外观模式-Facade Pattern/代码/无“外观模式”.swift: -------------------------------------------------------------------------------- 1 | //插排接口 2 | protocol SocketType { 3 | func on() -> Void 4 | func off() -> Void 5 | } 6 | //公牛插排 7 | class OXSocket: SocketType { 8 | func on() { 9 | print("公牛开关已打开") 10 | } 11 | 12 | func off() { 13 | print("公牛开关已关闭") 14 | } 15 | } 16 | 17 | //笔记本接口 18 | protocol ComputerType { 19 | func startUp() -> Void 20 | func shutdown() -> Void 21 | } 22 | 23 | //MacBookPro 24 | class MacBookPro: ComputerType { 25 | func startUp() { 26 | print("OS X 已启动") 27 | } 28 | 29 | func shutdown() { 30 | print("OS X 已关闭") 31 | } 32 | } 33 | 34 | 35 | //显示器接口 36 | protocol DisplayDeviceType { 37 | func on() -> Void 38 | func off() -> Void 39 | } 40 | 41 | //三星显示器 42 | class SamsungDisplay: DisplayDeviceType { 43 | func on() { 44 | print("三星显示器已打开") 45 | } 46 | 47 | func off() { 48 | print("三星显示器已关闭") 49 | } 50 | } 51 | 52 | 53 | //创建所需的对象 54 | let oxSocket: SocketType = OXSocket() 55 | let macBookPro: ComputerType = MacBookPro() 56 | let samsungDisplay: DisplayDeviceType = SamsungDisplay() 57 | 58 | 59 | print("每天上班要做的三件事情:") 60 | oxSocket.on() 61 | macBookPro.startUp() 62 | samsungDisplay.on() 63 | 64 | print("\n每天下班要做的事情:") 65 | samsungDisplay.off() 66 | macBookPro.shutdown() 67 | oxSocket.off() 68 | 69 | -------------------------------------------------------------------------------- /外观模式-Facade Pattern/类图/外观模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/外观模式-Facade Pattern/类图/外观模式.png -------------------------------------------------------------------------------- /外观模式-Facade Pattern/类图/无外观模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/外观模式-Facade Pattern/类图/无外观模式.png -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /示例代码/工厂方法模式.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DesignPatternDemo 3 | // 4 | // Created by Mr.LuDashi on 16/4/12. 5 | // Copyright © 2016年 ZeluLi. All rights reserved. 6 | // 7 | 8 | import Foundation 9 | 10 | enum WeaponTypeEnumeration { 11 | case AK, HK, AWP 12 | } 13 | 14 | protocol WeaponType { 15 | func fire() -> String 16 | } 17 | 18 | class AK: WeaponType { 19 | func fire() -> String { 20 | return "AK: Fire" 21 | } 22 | } 23 | 24 | class AWP: WeaponType { 25 | func fire() -> String { 26 | return "AWP: Fire" 27 | } 28 | } 29 | 30 | class HK: WeaponType { 31 | func fire() -> String { 32 | return "HK: Fire" 33 | } 34 | } 35 | 36 | //=========工厂方法模式(Factory Method Pattern)======== 37 | /// 工厂方法模式:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。 38 | //依赖倒置原则:要依赖抽象,不要依赖具体类 39 | 40 | ///使用“装饰者模式”为武器添加不同的装饰(生产厂商) 41 | 42 | class WeaponDecorator: WeaponType { 43 | var weapon: WeaponType! = nil 44 | init(weapon: WeaponType) { 45 | self.weapon = weapon 46 | } 47 | 48 | func fire() -> String { 49 | return weapon.fire() 50 | } 51 | 52 | } 53 | ///添加德国厂商装饰 54 | class GermanyDecorator: WeaponDecorator { 55 | override func fire() -> String { 56 | return "德国造:" + self.weapon.fire() 57 | } 58 | } 59 | 60 | /// 添加美国厂商装饰 61 | class AmericaDecorator: WeaponDecorator { 62 | override func fire() -> String { 63 | return "美国造:" + weapon.fire() 64 | } 65 | } 66 | 67 | 68 | 69 | /** 70 | * 武器用户的接口 71 | */ 72 | 73 | protocol WeaponUser { 74 | func fireWithType(weaponType: WeaponTypeEnumeration) 75 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType! 76 | } 77 | 78 | // MARK: - 为fireWithType方法添加默认实现 79 | extension WeaponUser { 80 | func fireWithType(weaponType: WeaponTypeEnumeration) { 81 | let weapon: WeaponType = createWeaponWithType(weaponType) 82 | print(weapon.fire()) 83 | } 84 | } 85 | 86 | 87 | /// 德国用户:使用德国造 88 | class GermanyWeaponUser: WeaponUser { 89 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType! { 90 | var weapon: WeaponType 91 | 92 | switch weaponType { 93 | case .AK: 94 | weapon = GermanyDecorator(weapon: AK()) 95 | case .HK: 96 | weapon = GermanyDecorator(weapon: HK()) 97 | case .AWP: 98 | weapon = GermanyDecorator(weapon: AWP()) 99 | } 100 | return weapon 101 | } 102 | } 103 | 104 | /// 美国用户:使用美国造 105 | class AmericaWeaponUser: WeaponUser { 106 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType! { 107 | var weapon: WeaponType 108 | 109 | switch weaponType { 110 | case .AK: 111 | weapon = AmericaDecorator(weapon: AK()) 112 | case .HK: 113 | weapon = AmericaDecorator(weapon: HK()) 114 | case .AWP: 115 | weapon = AmericaDecorator(weapon: AWP()) 116 | } 117 | return weapon 118 | } 119 | } 120 | 121 | var user: WeaponUser = GermanyWeaponUser() 122 | user.fireWithType(.AK) 123 | 124 | user = AmericaWeaponUser() 125 | user.fireWithType(.AK) 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /示例代码/抽象工厂+工厂方法模式.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DesignPatternDemo 3 | // 4 | // Created by Mr.LuDashi on 16/4/12. 5 | // Copyright © 2016年 ZeluLi. All rights reserved. 6 | // 7 | 8 | import Foundation 9 | 10 | /** 11 | * 抽象工厂模式(Abstract Factory) 12 | * 提供一个接口,用于创建相关或者依赖对象的家族,而不需要明确指向具体类 13 | */ 14 | enum WeaponTypeEnumeration { 15 | case AK, HK, AWP 16 | } 17 | 18 | protocol WeaponType { 19 | func fire() -> String 20 | } 21 | 22 | class AK: WeaponType { 23 | func fire() -> String { 24 | return "AK: Fire" 25 | } 26 | } 27 | 28 | class AWP: WeaponType { 29 | func fire() -> String { 30 | return "AWP: Fire" 31 | } 32 | } 33 | 34 | class HK: WeaponType { 35 | func fire() -> String { 36 | return "HK: Fire" 37 | } 38 | } 39 | 40 | 41 | class WeaponDecorator: WeaponType { 42 | var weapon: WeaponType! = nil 43 | init(weapon: WeaponType) { 44 | self.weapon = weapon 45 | } 46 | 47 | func fire() -> String { 48 | return weapon.fire() 49 | } 50 | 51 | } 52 | ///添加德国厂商装饰 53 | class GermanyDecorator: WeaponDecorator { 54 | override func fire() -> String { 55 | return "德国造:" + self.weapon.fire() 56 | } 57 | } 58 | 59 | /// 添加美国厂商装饰 60 | class AmericaDecorator: WeaponDecorator { 61 | override func fire() -> String { 62 | return "美国造:" + weapon.fire() 63 | } 64 | } 65 | 66 | 67 | 68 | /** 69 | * 创建抽象工厂(工厂接口) 70 | */ 71 | protocol WeaponFactoryType { 72 | func createAK() -> WeaponType 73 | func createAWP() -> WeaponType 74 | func createHK() -> WeaponType 75 | 76 | } 77 | 78 | /// 美国兵工厂:生产”美国造“系列的武器 79 | class AmericanWeaponFactory: WeaponFactoryType { 80 | func createAK() -> WeaponType { 81 | return AmericaDecorator(weapon: AK()) 82 | } 83 | 84 | func createAWP() -> WeaponType { 85 | return AmericaDecorator(weapon: AWP()) 86 | } 87 | 88 | func createHK() -> WeaponType { 89 | return AmericaDecorator(weapon: HK()) 90 | } 91 | } 92 | 93 | /// 德国兵工厂:生产”德国造“系列的武器 94 | class GermanyWeaponFactory: WeaponFactoryType { 95 | 96 | func createAK() -> WeaponType { 97 | return GermanyDecorator(weapon: AK()) 98 | } 99 | 100 | func createAWP() -> WeaponType { 101 | return GermanyDecorator(weapon: AWP()) 102 | } 103 | 104 | func createHK() -> WeaponType { 105 | return GermanyDecorator(weapon: HK()) 106 | } 107 | } 108 | 109 | 110 | /** 111 | * 抽象工厂 + 工厂方法, 使用工厂方法模式重写WeaponUser类的结构 112 | */ 113 | 114 | 115 | protocol WeaponUserType { 116 | 117 | func fireWithType(weaponType: WeaponTypeEnumeration) 118 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType! 119 | 120 | //工厂方法 121 | func createWeaponFactory() -> WeaponFactoryType 122 | 123 | } 124 | 125 | // MARK: - 为fireWithType方法添加默认实现 126 | extension WeaponUserType { 127 | func fireWithType(weaponType: WeaponTypeEnumeration) { 128 | let weapon: WeaponType = createWeaponWithType(weaponType) 129 | print(weapon.fire()) 130 | } 131 | 132 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType! { 133 | var weapon: WeaponType 134 | 135 | switch weaponType { 136 | case .AK: 137 | weapon = createWeaponFactory().createAK() 138 | case .AWP: 139 | weapon = createWeaponFactory().createAWP() 140 | case .HK: 141 | weapon = createWeaponFactory().createHK() 142 | } 143 | return weapon 144 | } 145 | 146 | } 147 | 148 | 149 | class AmericanWeaponUser: WeaponUserType { 150 | func createWeaponFactory() -> WeaponFactoryType { 151 | return AmericanWeaponFactory() 152 | } 153 | } 154 | 155 | class GermanyWeaponUser: WeaponUserType { 156 | func createWeaponFactory() -> WeaponFactoryType { 157 | return GermanyWeaponFactory() 158 | } 159 | } 160 | 161 | var user: WeaponUserType = AmericanWeaponUser() 162 | user.fireWithType(.AK) 163 | user.fireWithType(.AWP) 164 | user.fireWithType(.HK) 165 | 166 | user = GermanyWeaponUser() 167 | user.fireWithType(.AK) 168 | user.fireWithType(.AWP) 169 | user.fireWithType(.HK) 170 | 171 | -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /示例代码/抽象工厂模式.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DesignPatternDemo 3 | // 4 | // Created by Mr.LuDashi on 16/4/12. 5 | // Copyright © 2016年 ZeluLi. All rights reserved. 6 | // 7 | 8 | import Foundation 9 | 10 | /** 11 | * 抽象工厂模式(Abstract Factory) 12 | * 提供一个接口,用于创建相关或者依赖对象的家族,而不需要明确指向具体类 13 | */ 14 | enum WeaponTypeEnumeration { 15 | case AK, HK, AWP 16 | } 17 | 18 | protocol WeaponType { 19 | func fire() -> String 20 | } 21 | 22 | class AK: WeaponType { 23 | func fire() -> String { 24 | return "AK: Fire" 25 | } 26 | } 27 | 28 | class AWP: WeaponType { 29 | func fire() -> String { 30 | return "AWP: Fire" 31 | } 32 | } 33 | 34 | class HK: WeaponType { 35 | func fire() -> String { 36 | return "HK: Fire" 37 | } 38 | } 39 | 40 | 41 | class WeaponDecorator: WeaponType { 42 | var weapon: WeaponType! = nil 43 | init(weapon: WeaponType) { 44 | self.weapon = weapon 45 | } 46 | 47 | func fire() -> String { 48 | return weapon.fire() 49 | } 50 | 51 | } 52 | ///添加德国厂商装饰 53 | class GermanyDecorator: WeaponDecorator { 54 | override func fire() -> String { 55 | return "德国造:" + self.weapon.fire() 56 | } 57 | } 58 | 59 | /// 添加美国厂商装饰 60 | class AmericaDecorator: WeaponDecorator { 61 | override func fire() -> String { 62 | return "美国造:" + weapon.fire() 63 | } 64 | } 65 | 66 | 67 | 68 | /** 69 | * 创建抽象工厂(工厂接口) 70 | */ 71 | protocol WeaponFactoryType { 72 | func createAK() -> WeaponType 73 | func createAWP() -> WeaponType 74 | func createHK() -> WeaponType 75 | 76 | } 77 | 78 | /// 美国兵工厂:生产”美国造“系列的武器 79 | class AmericanWeaponFactory: WeaponFactoryType { 80 | func createAK() -> WeaponType { 81 | return AmericaDecorator(weapon: AK()) 82 | } 83 | 84 | func createAWP() -> WeaponType { 85 | return AmericaDecorator(weapon: AWP()) 86 | } 87 | 88 | func createHK() -> WeaponType { 89 | return AmericaDecorator(weapon: HK()) 90 | } 91 | } 92 | 93 | /// 德国兵工厂:生产”德国造“系列的武器 94 | class GermanyWeaponFactory: WeaponFactoryType { 95 | 96 | func createAK() -> WeaponType { 97 | return GermanyDecorator(weapon: AK()) 98 | } 99 | 100 | func createAWP() -> WeaponType { 101 | return GermanyDecorator(weapon: AWP()) 102 | } 103 | 104 | func createHK() -> WeaponType { 105 | return GermanyDecorator(weapon: HK()) 106 | } 107 | } 108 | 109 | 110 | 111 | /// 对用户进行重写 112 | class WeaponUser { 113 | 114 | private var factory: WeaponFactoryType 115 | 116 | init(factory: WeaponFactoryType) { 117 | self.factory = factory 118 | } 119 | 120 | func setFactory(factory: WeaponFactoryType) { 121 | self.factory = factory 122 | } 123 | 124 | 125 | func fireWithType(weaponType: WeaponTypeEnumeration) { 126 | var weapon: WeaponType 127 | 128 | switch weaponType { 129 | case .AK: 130 | weapon = factory.createAK() 131 | case .AWP: 132 | weapon = factory.createAWP() 133 | case .HK: 134 | weapon = factory.createHK() 135 | } 136 | 137 | print(weapon.fire()) 138 | } 139 | } 140 | 141 | var user: WeaponUser = WeaponUser(factory: AmericanWeaponFactory()) 142 | user.fireWithType(.AK) 143 | user.fireWithType(.AWP) 144 | user.fireWithType(.HK) 145 | 146 | user.setFactory(GermanyWeaponFactory()) 147 | user.fireWithType(.AK) 148 | user.fireWithType(.AWP) 149 | user.fireWithType(.HK) 150 | -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /示例代码/无工厂模式.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DesignPatternDemo 3 | // 4 | // Created by Mr.LuDashi on 16/4/12. 5 | // Copyright © 2016年 ZeluLi. All rights reserved. 6 | // 7 | 8 | import Foundation 9 | 10 | enum WeaponTypeEnumeration { 11 | case AK, HK, AWP 12 | } 13 | 14 | protocol WeaponType { 15 | func fire() -> String 16 | } 17 | 18 | class AK: WeaponType { 19 | func fire() -> String { 20 | return "AK: Fire" 21 | } 22 | } 23 | 24 | class AWP: WeaponType { 25 | func fire() -> String { 26 | return "AWP: Fire" 27 | } 28 | } 29 | 30 | class HK: WeaponType { 31 | func fire() -> String { 32 | return "HK: Fire" 33 | } 34 | } 35 | 36 | class WeaponUser { 37 | func fireWithType(weaponType: WeaponTypeEnumeration) { 38 | var weapon: WeaponType 39 | 40 | switch weaponType { 41 | case .AK: 42 | weapon = AK() 43 | case .HK: 44 | weapon = HK() 45 | case .AWP: 46 | weapon = AWP() 47 | } 48 | 49 | print(weapon.fire()) 50 | } 51 | } 52 | 53 | 54 | let weaponUser: WeaponUser = WeaponUser() 55 | 56 | weaponUser.fireWithType(.AK) 57 | weaponUser.fireWithType(.AWP) 58 | 59 | 60 | -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /示例代码/简单工厂模式.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DesignPatternDemo 3 | // 4 | // Created by Mr.LuDashi on 16/4/12. 5 | // Copyright © 2016年 ZeluLi. All rights reserved. 6 | // 7 | 8 | import Foundation 9 | 10 | enum WeaponTypeEnumeration { 11 | case AK, HK, AWP 12 | } 13 | 14 | protocol WeaponType { 15 | func fire() -> String 16 | } 17 | 18 | class AK: WeaponType { 19 | func fire() -> String { 20 | return "AK: Fire" 21 | } 22 | } 23 | 24 | class AWP: WeaponType { 25 | func fire() -> String { 26 | return "AWP: Fire" 27 | } 28 | } 29 | 30 | class HK: WeaponType { 31 | func fire() -> String { 32 | return "HK: Fire" 33 | } 34 | } 35 | 36 | //=======简单工厂模式(Simple Factory Pattern)======== 37 | //使用“简单工厂模式”将变化的部分进行提取 38 | 39 | // WeaponFactory就是我们的简单工厂 40 | class WeaponFactory { 41 | 42 | func createWeaponWithType(weaponType: WeaponTypeEnumeration) -> WeaponType { 43 | var weapon: WeaponType 44 | 45 | switch weaponType { 46 | case .AK: 47 | weapon = AK() 48 | case .HK: 49 | weapon = HK() 50 | case .AWP: 51 | weapon = AWP() 52 | } 53 | 54 | return weapon 55 | } 56 | } 57 | 58 | class WeaponUser { 59 | var weaponFactory: WeaponFactory 60 | 61 | init(weaponFactory: WeaponFactory) { 62 | self.weaponFactory = weaponFactory 63 | } 64 | 65 | func fireWithType(weaponType: WeaponTypeEnumeration) { 66 | let weapon: WeaponType = weaponFactory.createWeaponWithType(weaponType) 67 | print(weapon.fire()) 68 | } 69 | } 70 | let weaponUser: WeaponUser = WeaponUser(weaponFactory: WeaponFactory()) 71 | 72 | weaponUser.fireWithType(.AK) 73 | weaponUser.fireWithType(.AWP) 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /类图/工厂方法模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/工厂模式-Factory Pattern /类图/工厂方法模式.png -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /类图/抽象工厂+工厂方法模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/工厂模式-Factory Pattern /类图/抽象工厂+工厂方法模式.png -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /类图/抽象工厂模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/工厂模式-Factory Pattern /类图/抽象工厂模式.png -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /类图/无工厂模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/工厂模式-Factory Pattern /类图/无工厂模式.png -------------------------------------------------------------------------------- /工厂模式-Factory Pattern /类图/简单工厂模式.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/工厂模式-Factory Pattern /类图/简单工厂模式.png -------------------------------------------------------------------------------- /模板方法模式-Template Method Pattern/代码/无模板方法.swift: -------------------------------------------------------------------------------- 1 | //模板方法模式 2 | //模板方法定义了一个算法的步骤,并允许子类为一个或者多个步骤提供实现 3 | //模板方法模式:在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。 4 | 5 | //醋溜土豆丝 6 | class FryShreddedPotatoes { 7 | func fryShreddedPotatoes() { 8 | reportTheDishNames() 9 | putSomeOil() 10 | putSomeGreenOnion() 11 | putPotatoes() 12 | putSaltAndVinegar() 13 | outOfThePan() 14 | } 15 | 16 | //报菜名 17 | func reportTheDishNames() { 18 | print("醋溜土豆丝:") 19 | } 20 | 21 | func putSomeOil() { 22 | print("往锅里放油!") 23 | } 24 | 25 | func putSomeGreenOnion() { 26 | print("放葱花爆香!") 27 | } 28 | 29 | func putPotatoes() { 30 | print("放土豆丝和青红椒丝!") 31 | } 32 | 33 | func putSaltAndVinegar() { 34 | print("放盐和醋!") 35 | } 36 | 37 | func outOfThePan() { 38 | print("出锅!\n") 39 | } 40 | } 41 | 42 | 43 | //清炒苦瓜 44 | class FryBitterGourd { 45 | 46 | func fryBitterGourd() { 47 | reportTheDishNames() 48 | putSomeOil() 49 | putSomeGreenOnion() 50 | putBitterGourd() 51 | putSalt() 52 | outOfThePan() 53 | } 54 | 55 | //报菜名 56 | func reportTheDishNames() { 57 | print("清炒苦瓜:") 58 | } 59 | 60 | func putSomeOil() { 61 | print("往锅里放油!") 62 | } 63 | 64 | func putSomeGreenOnion() { 65 | print("放葱花爆香!") 66 | } 67 | 68 | func putBitterGourd() { 69 | print("放苦瓜片和青红椒片!") 70 | } 71 | 72 | func putSalt() { 73 | print("放盐!") 74 | } 75 | 76 | func outOfThePan() { 77 | print("出锅!\n") 78 | } 79 | } 80 | 81 | 82 | 83 | let fryShreddedPotatoes: FryShreddedPotatoes = FryShreddedPotatoes() 84 | fryShreddedPotatoes.fryShreddedPotatoes() 85 | 86 | let fryBitterGourd: FryBitterGourd = FryBitterGourd() 87 | fryBitterGourd.fryBitterGourd() 88 | 89 | -------------------------------------------------------------------------------- /模板方法模式-Template Method Pattern/代码/有模板方法.swift: -------------------------------------------------------------------------------- 1 | 2 | //炒菜的接口 3 | protocol FryVegetablesType { 4 | func fry() //模板方法,在延展中给出默认实现 5 | func reportTheDishNames() //报菜名,在子类中给出实现 6 | func putSomeOil() //放油,在延展中给出默认实现 7 | func putSomeGreenOnion() //放葱花,在延展中给出默认实现 8 | func putVegetables() //放蔬菜,在子类中给出具体实现 9 | func putSpices() //放调料,在子类中给出具体实现 10 | func outOfThePan() //出锅,在延展中给出具体实现 11 | } 12 | 13 | //对炒菜接口提供的延展,给出了炒菜中共同的部分和“模板方法” 14 | extension FryVegetablesType { 15 | func fry() { 16 | reportTheDishNames() 17 | putSomeOil() 18 | putSomeGreenOnion() 19 | putVegetables() 20 | putSpices() 21 | outOfThePan() 22 | } 23 | 24 | func putSomeOil() { 25 | print("往锅里放油!") 26 | } 27 | 28 | func putSomeGreenOnion() { 29 | print("放葱花爆香!") 30 | } 31 | 32 | func outOfThePan() { 33 | print("出锅!\n") 34 | } 35 | } 36 | 37 | //醋溜土豆丝 38 | class FryShreddedPotatoes: FryVegetablesType { 39 | 40 | //报菜名 41 | func reportTheDishNames() { 42 | print("醋溜土豆丝:") 43 | } 44 | 45 | func putVegetables() { 46 | print("放土豆丝和青红椒丝!") 47 | } 48 | 49 | func putSpices() { 50 | print("放盐和醋!") 51 | } 52 | } 53 | 54 | 55 | //清炒苦瓜 56 | class FryBitterGourd: FryVegetablesType { 57 | func reportTheDishNames() { 58 | print("清炒苦瓜:") 59 | } 60 | 61 | func putVegetables() { 62 | print("放苦瓜片和青红椒片! ") 63 | } 64 | 65 | func putSpices() { 66 | print("放盐!") 67 | } 68 | } 69 | 70 | 71 | 72 | let fryShreddedPotatoes: FryShreddedPotatoes = FryShreddedPotatoes() 73 | fryShreddedPotatoes.fry() 74 | 75 | let fryBitterGourd: FryBitterGourd = FryBitterGourd() 76 | fryBitterGourd.fry() 77 | -------------------------------------------------------------------------------- /模板方法模式-Template Method Pattern/类图.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/模板方法模式-Template Method Pattern/类图.png -------------------------------------------------------------------------------- /状态模式-State Pattern/代码/无“状态模式”ATM.swift: -------------------------------------------------------------------------------- 1 | //状态模式:允许对象在内部状态改变时改变它的行为,对象看起来好像修够了它的类。 2 | 3 | enum ATMState { 4 | case NoBankCardState //无卡 5 | case HasBankCardState //有卡 6 | case DecodingState //解密 7 | case FetchMoneyState //可取款状态 8 | case OutMoneyState //取款 9 | case InsufficientBalanceState //余额不足 10 | } 11 | 12 | 13 | class ATM { 14 | var state: ATMState = .NoBankCardState //ATM的状态默认是无卡状态 15 | var money: UInt = 0 16 | var inputMoney: UInt = 0 17 | 18 | //插卡动作 19 | func insertBankCard() { 20 | switch state { 21 | case .NoBankCardState: 22 | state = .HasBankCardState 23 | money = 10_000 24 | print("已插入银行卡, 现在可以输入密码或者退卡") 25 | 26 | case .HasBankCardState: 27 | print("目前已有银行卡,可以输入密码进行取款") 28 | 29 | case .DecodingState: 30 | print("目前处于解密状态,可输入金额进行取款") 31 | 32 | case .FetchMoneyState: 33 | print("目前处于可取款状态,请点击确认按钮进行取款") 34 | 35 | case .OutMoneyState: 36 | print("已取款,你可以选择输入密码再次取款,或者退卡") 37 | 38 | case .InsufficientBalanceState: 39 | print("余额不足,你可以选择输入密码再次取款,或者退卡") 40 | } 41 | } 42 | 43 | //退卡动作 44 | func backBankCard() { 45 | switch state { 46 | case .NoBankCardState: 47 | print("无银行卡,无法退卡") 48 | case .HasBankCardState: 49 | fallthrough 50 | case .DecodingState: 51 | fallthrough 52 | case .FetchMoneyState: 53 | fallthrough 54 | case .InsufficientBalanceState: 55 | fallthrough 56 | case .OutMoneyState: 57 | state = .NoBankCardState 58 | print("已退卡") 59 | } 60 | } 61 | 62 | func inputPassword() { 63 | switch state { 64 | case .NoBankCardState: 65 | print("无银行卡,无法进行输入密码操作,请插入银行卡") 66 | 67 | case .HasBankCardState: 68 | state = .DecodingState 69 | print("密码校验成功,现在可以输入金额进行取款") 70 | 71 | case .DecodingState: 72 | print("已输入密码,现在可以输入金额进行取款") 73 | case .FetchMoneyState: 74 | print("已输入取款金额,现在可进行取款") 75 | 76 | case .OutMoneyState: 77 | state = .DecodingState 78 | print("已取款,再次输入密码进行取款") 79 | 80 | case .InsufficientBalanceState: 81 | state = .DecodingState 82 | print("余额不足,再次输入密码进行取款") 83 | } 84 | } //输入密码动作 85 | func inputMoney(money: UInt) { 86 | switch state { 87 | case .NoBankCardState: 88 | print("无银行卡,无法进行输入取款金额,请插入银行卡") 89 | 90 | case .HasBankCardState: 91 | print("请输入密码后方可进行取款操作") 92 | 93 | case .DecodingState: 94 | self.state = .FetchMoneyState 95 | self.inputMoney = money 96 | print("输入金额成功") 97 | 98 | case .FetchMoneyState: 99 | print("已输入取款金额,现在可进行取款") 100 | case .OutMoneyState: 101 | print("已取款,你可以选择输入密码再次取款,或者退卡") 102 | case .InsufficientBalanceState: 103 | print("余额不足,你可以选择输入密码再次取款,或者退卡") 104 | } 105 | } //输入金额动作 106 | func tapOkButton() { 107 | switch state { 108 | case .NoBankCardState: 109 | print("无银行卡,请插入银行卡") 110 | case .HasBankCardState: 111 | print("请输入密码后方可进行取款操作") 112 | case .DecodingState: 113 | print("已输入密码,现在可以输入金额进行取款") 114 | 115 | case .FetchMoneyState: 116 | if inputMoney > money { 117 | state = .InsufficientBalanceState 118 | print("余额不足,你可以选择输入密码再次取款,或者退卡") 119 | } else { 120 | state = .OutMoneyState 121 | print("已取款,你可以选择输入密码再次取款,或者退卡") 122 | } 123 | 124 | case .OutMoneyState: 125 | print("已取款,你可以选择输入密码再次取款,或者退卡") 126 | case .InsufficientBalanceState: 127 | print("余额不足,你可以选择输入密码再次取款,或者退卡") 128 | } 129 | 130 | } //确认提款动作 131 | } 132 | 133 | 134 | 135 | 136 | let atm = ATM() 137 | 138 | print("=======无卡状态下插入银行卡========") 139 | atm.insertBankCard() 140 | 141 | print("\n=======有卡状态下再次插入卡========") 142 | atm.insertBankCard() 143 | 144 | print("\n=======有卡状态输入密码========") 145 | atm.inputPassword() 146 | atm.inputMoney(100) 147 | atm.tapOkButton() 148 | 149 | print("\n=======取款后再次输入密码进行提款========") 150 | atm.inputPassword() 151 | atm.inputMoney(100000) 152 | atm.tapOkButton() 153 | 154 | 155 | print("\n=======退卡========") 156 | atm.backBankCard() 157 | 158 | print("\n====无卡时调用输入密码操作=====") 159 | atm.inputPassword() 160 | -------------------------------------------------------------------------------- /状态模式-State Pattern/代码/有“状态模式”ATM.swift: -------------------------------------------------------------------------------- 1 | //==================使用状态模式进行重构====== 2 | //状态模式:允许对象在内部状态改变时改变它的行为,对象看起来好像修够了它的类。 3 | 4 | enum ATMState { 5 | case NoBankCardState //无卡 6 | case HasBankCardState //有卡 7 | case DecodingState //解密 8 | case FetchMoneyState //可取款状态 9 | case OutMoneyState //取款 10 | case InsufficientBalanceState //余额不足 11 | } 12 | 13 | protocol StateType { 14 | func insertBankCard() 15 | func backBankCard() 16 | func inputPassword() 17 | func inputMoney(money: UInt) 18 | func tapOkButton() 19 | } 20 | 21 | protocol ATMType: StateType { 22 | func getCardMoney() -> UInt 23 | func getInputMoney() -> UInt 24 | func changeState(state: ATMState) 25 | } 26 | 27 | 28 | class BaseStateClass: StateType { 29 | private var atm: ATMType 30 | 31 | init(atm: ATMType) { 32 | self.atm = atm 33 | } 34 | 35 | func insertBankCard() {} 36 | func backBankCard() {} 37 | func inputPassword() {} 38 | func inputMoney(money: UInt) {} 39 | func tapOkButton() {} 40 | 41 | } 42 | 43 | //无卡状态类 44 | class NoBankCardState: BaseStateClass { 45 | 46 | override func insertBankCard() { 47 | print("已插入银行卡, 现在可以输入密码或者退卡") 48 | atm.changeState(.HasBankCardState) 49 | } 50 | 51 | override func backBankCard() { 52 | print("无银行卡,无法退卡") 53 | } 54 | 55 | override func inputPassword() { 56 | print("无银行卡,无法进行输入密码操作,请插入银行卡") 57 | } 58 | override func inputMoney(money: UInt) { 59 | print("无银行卡,无法进行输入取款金额,请插入银行卡") 60 | } 61 | 62 | override func tapOkButton() { 63 | print("无银行卡,无法进行取款操作,请插入银行卡") 64 | } 65 | } 66 | 67 | //有卡状态类 68 | class HasBankCardState: BaseStateClass { 69 | 70 | override func insertBankCard() { 71 | print("目前已经插入了一张银行卡,不可以再次插入,现在可以输入密码进行取款") 72 | } 73 | 74 | override func backBankCard() { 75 | print("已退卡") 76 | } 77 | 78 | override func inputPassword() { 79 | atm.changeState(.DecodingState) 80 | print("密码校验成功,现在可以输入金额进行取款") 81 | } 82 | 83 | override func inputMoney(money: UInt) { 84 | print("你还没有进行密码验证,请输入密码后方可输入取款金额") 85 | } 86 | 87 | override func tapOkButton() { 88 | print("你还没有进行密码验证以及输入金额操作,请输入上述步骤后方可进行取款操作") 89 | } 90 | } 91 | //解密状态类 92 | class DecodingState: BaseStateClass { 93 | 94 | override func insertBankCard() { 95 | print("目前已经插入了一张银行卡,不可以再次插入,现在可以输入金额进行取款") 96 | } 97 | 98 | override func backBankCard() { 99 | print("已退卡") 100 | } 101 | 102 | override func inputPassword() { 103 | print("你的密码已经校验成功,请不要重复提交密码,现在可以输入金额进行取款") 104 | } 105 | 106 | override func inputMoney(money: UInt) { 107 | atm.changeState(.FetchMoneyState) 108 | print("输入金额成功,现在可点击确认按钮进行取款操作") 109 | } 110 | 111 | override func tapOkButton() { 112 | print("你还没有输入金额操作,请输入上述步骤后方可进行取款操作") 113 | } 114 | } 115 | //取款状态类 116 | class FetchMoneyState: BaseStateClass { 117 | 118 | override func insertBankCard() { 119 | print("目前已经插入了一张银行卡,不可以再次插入,现在可以点击按钮进行取款") 120 | } 121 | 122 | override func backBankCard() { 123 | print("已退卡") 124 | } 125 | 126 | override func inputPassword() { 127 | print("你的密码已经校验成功,请不要重复提交密码,现在可以点击按钮进行取款") 128 | } 129 | 130 | override func inputMoney(money: UInt) { 131 | print("已输入提款金额,请不要重复提交,现在可点击确认按钮进行取款操作") 132 | } 133 | 134 | override func tapOkButton() { 135 | if atm.getInputMoney() > atm.getCardMoney() { 136 | atm.changeState(.InsufficientBalanceState) 137 | print("余额不足,你可以选择输入密码再次取款,或者退卡") 138 | } else { 139 | atm.changeState(.OutMoneyState) 140 | print("已取款,你可以选择输入密码再次取款,或者退卡") 141 | } 142 | 143 | } 144 | } 145 | //已取款状态类 146 | class OutMoneyState: BaseStateClass { 147 | 148 | override func insertBankCard() { 149 | print("目前已经插入了一张银行卡,不可以再次插入,现在可以退卡或再次输入密码进行取款操作") 150 | } 151 | 152 | override func backBankCard() { 153 | print("已退卡") 154 | } 155 | 156 | override func inputPassword() { 157 | atm.changeState(.DecodingState) 158 | print("密码校验成功,现在可以输入金额进行取款") 159 | 160 | } 161 | 162 | override func inputMoney(money: UInt) { 163 | print("已输入提款金额,请不要重复提交,现在可点击确认按钮进行取款操作") 164 | } 165 | 166 | override func tapOkButton() { 167 | print("取款成功,现在可以退卡或再次输入密码进行取款操作") 168 | } 169 | } 170 | //余额不足状态类 171 | class InsufficientBalanceState: BaseStateClass { 172 | 173 | override func insertBankCard() { 174 | print("目前已经插入了一张银行卡,不可以再次插入,现在可以退卡或再次输入密码进行取款操作") 175 | } 176 | 177 | override func backBankCard() { 178 | print("已退卡") 179 | } 180 | 181 | override func inputPassword() { 182 | atm.changeState(.DecodingState) 183 | print("密码校验成功,现在可以输入金额进行取款") 184 | 185 | } 186 | 187 | override func inputMoney(money: UInt) { 188 | print("已输入提款金额,请不要重复提交,现在可点击确认按钮进行取款操作") 189 | } 190 | 191 | override func tapOkButton() { 192 | print("余额不足,无法取款,现在可以退卡或再次输入密码进行取款操作") 193 | } 194 | } 195 | 196 | class ATM: ATMType { 197 | private var stateObject: StateType? 198 | private var cardMoney: UInt = 0 199 | private var inputMoney: UInt = 0 200 | 201 | init() { 202 | self.changeState(.NoBankCardState) 203 | } 204 | 205 | func getCardMoney() -> UInt { 206 | return cardMoney 207 | } 208 | func getInputMoney() -> UInt { 209 | return inputMoney 210 | } 211 | func changeState(state: ATMState) { 212 | switch state { 213 | case .NoBankCardState: 214 | stateObject = NoBankCardState(atm: self) 215 | case .HasBankCardState: 216 | stateObject = HasBankCardState(atm: self) 217 | case .DecodingState: 218 | stateObject = DecodingState(atm: self) 219 | case .FetchMoneyState: 220 | stateObject = FetchMoneyState(atm: self) 221 | case .OutMoneyState: 222 | stateObject = OutMoneyState(atm: self) 223 | case .InsufficientBalanceState: 224 | stateObject = InsufficientBalanceState(atm: self) 225 | } 226 | } 227 | 228 | func insertBankCard() { 229 | self.cardMoney = 20000 230 | stateObject?.insertBankCard() 231 | } 232 | 233 | func backBankCard() { 234 | stateObject?.backBankCard() 235 | } 236 | 237 | func inputPassword() { 238 | stateObject?.inputPassword() 239 | } 240 | 241 | func inputMoney(money: UInt) { 242 | inputMoney = money 243 | stateObject?.inputMoney(money) 244 | } 245 | 246 | func tapOkButton() { 247 | stateObject?.tapOkButton() 248 | } 249 | } 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | let atm = ATM() 262 | 263 | print("=======无卡状态下插入银行卡========") 264 | atm.insertBankCard() 265 | 266 | print("\n=======有卡状态下再次插入卡========") 267 | atm.insertBankCard() 268 | 269 | print("\n=======有卡状态输入密码========") 270 | atm.inputPassword() 271 | atm.inputMoney(100) 272 | atm.tapOkButton() 273 | 274 | print("\n=======取款后再次输入密码进行提款========") 275 | atm.inputPassword() 276 | atm.inputMoney(100000) 277 | atm.tapOkButton() 278 | 279 | 280 | print("\n=======退卡========") 281 | atm.backBankCard() 282 | 283 | print("\n====无卡时调用输入密码操作=====") 284 | atm.inputPassword() 285 | -------------------------------------------------------------------------------- /状态模式-State Pattern/类图/屏幕快照 2016-04-28 下午4.13.33.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/状态模式-State Pattern/类图/屏幕快照 2016-04-28 下午4.13.33.png -------------------------------------------------------------------------------- /状态模式-State Pattern/类图/屏幕快照 2016-04-28 下午5.01.38.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/状态模式-State Pattern/类图/屏幕快照 2016-04-28 下午5.01.38.png -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/策略模式-Strategy Pattern/01.png -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/策略模式-Strategy Pattern/02.png -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/策略模式-Strategy Pattern/03.png -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/Duck1.swift: -------------------------------------------------------------------------------- 1 | class Duck { 2 | func swim() { 3 | print("鸭子游泳喽~") 4 | } 5 | 6 | func quack() { 7 | print("鸭子呱呱叫") 8 | } 9 | 10 | func display(){ 11 | } 12 | } 13 | 14 | class MallarDuck: Duck { 15 | override func display() { 16 | print("我是绿头鸭子") 17 | } 18 | } 19 | 20 | class RedHeadDuck: Duck { 21 | override func display() { 22 | print("我是红头鸭子") 23 | } 24 | } 25 | 26 | class RubberDuck: Duck { 27 | 28 | 29 | override func display() { 30 | print("橡皮鸭") 31 | } 32 | } 33 | 34 | 35 | 36 | /** 37 | * 现在要为某些鸭子添加上飞的方法,该如何去做呢? 38 | * 一些假的鸭子是不能飞的 39 | * 1、在基类中添加fly(),在不会飞的鸭子中重新fly, 但是这样的话,子类中会有些无用的方法 40 | 2.使用接口,需要实现fly()的鸭子,实现接口即可,但是会产生重复的带。 41 | */ 42 | -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/Duck2.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * 现在要为某些鸭子添加上飞的方法,该如何去做呢? 3 | * 一些假的鸭子是不能飞的 4 | * 1、在基类中添加fly(),在不会飞的鸭子中重新fly, 但是这样的话,子类中会有些无用的方法 5 | 2.使用接口,需要实现fly()的鸭子,实现接口即可,但是会产生重复的带。 6 | */ 7 | 8 | 9 | 10 | 11 | //解决方案1: 使用Swift中国的协议延展来做 12 | protocol Flyable { 13 | func fly(); 14 | } 15 | 16 | //为协议添加,默认实现 17 | extension Flyable { 18 | func fly() { 19 | print("我是会飞的鸭子,我用翅膀飞") 20 | } 21 | } 22 | 23 | class Duck { 24 | func swim() { 25 | print("鸭子游泳喽~") 26 | } 27 | 28 | func quack() { 29 | print("鸭子呱呱叫") 30 | } 31 | 32 | func display(){ 33 | } 34 | } 35 | 36 | //为绿头鸭子实现会飞的功能 37 | class MallarDuck: Duck, Flyable { 38 | override func display() { 39 | print("我是绿头鸭子") 40 | } 41 | } 42 | 43 | class RedHeadDuck: Duck, Flyable { 44 | override func display() { 45 | print("我是红头鸭子") 46 | } 47 | } 48 | 49 | class RubberDuck: Duck { 50 | 51 | override func display() { 52 | print("橡皮鸭") 53 | } 54 | } 55 | 56 | let mallarDuck: MallarDuck = MallarDuck() 57 | mallarDuck.fly() 58 | 59 | 60 | 61 | 62 | 63 | 64 | //解决方案二:使用多态,行为代理--------策略模式(Strategy Pattern)-------------- 65 | //设计原则1:找出应用中可能需要变化之处,把它们独立出来,不要和那些不变的代码混在一起。 66 | //设计原则2:针对接口编程,而不是针对实现编程 67 | //设计原则3:多用组合,少用继承 68 | 69 | 70 | //飞的行为协议 71 | protocol Flyable { 72 | func fly(); 73 | } 74 | 75 | //使用翅膀飞的类 76 | class FlyWithWings: Flyable { 77 | func fly() { 78 | print("我是会飞的鸭子, 我用翅膀飞呀飞") 79 | } 80 | } 81 | //什么都不会飞 82 | class FlyNoWay: Flyable { 83 | func fly() { 84 | print("我是不会飞的鸭子") 85 | } 86 | } 87 | 88 | class Duck { 89 | 90 | //添加行为委托代理者 91 | var flyBehavior: Flyable! = nil 92 | 93 | func setFlyBehavior(flyBehavior: Flyable) { 94 | self.flyBehavior = flyBehavior 95 | } 96 | 97 | func swim() { 98 | print("鸭子游泳喽~") 99 | } 100 | 101 | func quack() { 102 | print("鸭子呱呱叫") 103 | } 104 | 105 | func display(){ 106 | } 107 | 108 | //执行飞的行为 109 | func performFly() { 110 | guard (self.flyBehavior != nil) else { 111 | return; 112 | } 113 | self.flyBehavior.fly(); 114 | } 115 | } 116 | 117 | //为绿头鸭子实现会飞的功能 118 | class MallarDuck: Duck { 119 | 120 | override init() { 121 | super.init() 122 | self.setFlyBehavior(FlyWithWings()) 123 | } 124 | 125 | override func display() { 126 | print("我是绿头鸭子") 127 | } 128 | } 129 | 130 | class RedHeadDuck: Duck { 131 | override init() { 132 | super.init() 133 | self.setFlyBehavior(FlyWithWings()) 134 | } 135 | override func display() { 136 | print("我是红头鸭子") 137 | } 138 | } 139 | 140 | class RubberDuck: Duck { 141 | override init() { 142 | super.init() 143 | self.setFlyBehavior(FlyNoWay()) 144 | } 145 | 146 | override func display() { 147 | print("橡皮鸭") 148 | } 149 | } 150 | 151 | var duck: Duck = MallarDuck() 152 | duck.performFly() 153 | 154 | duck.setFlyBehavior(FlyNoWay()) 155 | duck.performFly() 156 | 157 | 158 | 159 | //现在需求又来了,要创建一个模型的鸭子,并且该鸭子会飞 160 | //在上面的基础上进行扩充是非常简单的 161 | class ModelDuck: Duck { 162 | override init() { 163 | super.init() 164 | self.setFlyBehavior(FlyWithWings()) 165 | } 166 | 167 | override func display() { 168 | print("鸭子模型") 169 | } 170 | } 171 | 172 | duck = ModelDuck() 173 | duck.performFly() 174 | 175 | 176 | 177 | //需求又来了,要给模型的鸭子装发动机,支持他飞,好,扩充就比较简单了 178 | //为鸭子创建新的动力系统 179 | class FlyAutomaticPower: Flyable { 180 | func fly() { 181 | print("我是用发动机飞的鸭子") 182 | } 183 | } 184 | //指定新的动力系统 185 | duck.setFlyBehavior(FlyAutomaticPower()) 186 | duck.performFly() 187 | 188 | 189 | /* 190 | 策略模式: 191 | 定义了算法族(就是上面鸭子的各种飞行行为),分别封装了起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户 192 | */ 193 | -------------------------------------------------------------------------------- /策略模式-Strategy Pattern/StrategyPattern.swift: -------------------------------------------------------------------------------- 1 | //实现角色可以使用的不同的攻击行为,也就是不同的攻击策略 2 | //武器策略 3 | protocol WeaponBehavior { 4 | func useWeapon(); 5 | } 6 | 7 | class AWPBehavior: WeaponBehavior { 8 | func useWeapon() { 9 | print("大狙---biu~biu~") 10 | } 11 | } 12 | 13 | class HK48Behavior: WeaponBehavior { 14 | func useWeapon() { 15 | print("HK48---tu~tu~tu~") 16 | } 17 | } 18 | 19 | class PistolBehavior: WeaponBehavior { 20 | func useWeapon() { 21 | print("手枪--pa~pa~pa~") 22 | } 23 | } 24 | 25 | //上面定义了一系列的武器策略 26 | //下面是用户================= 27 | 28 | class Character { 29 | //默认是配备的是手枪 30 | private var weapon: WeaponBehavior! = PistolBehavior() 31 | 32 | func setWeapon(weapon: WeaponBehavior) { 33 | self.weapon = weapon 34 | } 35 | 36 | //换手枪 37 | func changePistol() { 38 | self.setWeapon(PistolBehavior()); 39 | } 40 | 41 | func fire() { 42 | guard self.weapon != nil else { 43 | return 44 | } 45 | self.weapon.useWeapon() 46 | } 47 | } 48 | 49 | //中尉只配备了手枪和HK48 50 | class Lieutenant: Character { 51 | 52 | override init() { 53 | super.init(); 54 | } 55 | 56 | //切换武器(策略):换HK 57 | func changeHK() { 58 | self.setWeapon(HK48Behavior()); 59 | } 60 | } 61 | 62 | //上尉尉只配备了手枪和大狙 63 | class Captain: Character { 64 | 65 | override init() { 66 | super.init(); 67 | } 68 | //切换武器(策略):换大狙 69 | func changeAWP() { 70 | self.setWeapon(AWPBehavior()); 71 | } 72 | } 73 | 74 | 75 | 76 | //中尉 77 | let lieutenant: Lieutenant = Lieutenant() 78 | lieutenant.fire() 79 | 80 | print("\n手枪火力不行,得换HK48\n") 81 | 82 | lieutenant.changeHK() 83 | lieutenant.fire() 84 | -------------------------------------------------------------------------------- /组合模式-Composite Pattern/代码/File.swift: -------------------------------------------------------------------------------- 1 | //组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象已经对象组合 2 | 3 | 4 | protocol FileType { 5 | func getFileName() -> String 6 | func addFile(file: FileType) 7 | func deleteFile(file: FileType) 8 | func display() 9 | } 10 | 11 | extension FileType { 12 | func addFile(file: FileType) {} 13 | func deleteFile(file: FileType){} 14 | } 15 | 16 | class Folder: FileType { 17 | private var files: Dictionary = Dictionary() 18 | private var folderName: String 19 | init(folderName: String) { 20 | self.folderName = folderName 21 | } 22 | 23 | func getFileName() -> String { 24 | return self.folderName 25 | } 26 | 27 | 28 | func addFile(file: FileType) { 29 | files[file.getFileName()] = file 30 | } 31 | 32 | func deleteFile(file: FileType) { 33 | files.removeValueForKey(file.getFileName()) 34 | } 35 | 36 | func display() { 37 | let allKeys = Array(files.keys) 38 | print(getFileName()) 39 | for i in 0.. String { 52 | return self.fileName 53 | } 54 | 55 | func display() { 56 | print(getFileName()) 57 | } 58 | 59 | } 60 | 61 | class SwiftFile: BaseFile { 62 | } 63 | 64 | class ObjCFile: BaseFile { 65 | } 66 | 67 | 68 | 69 | 70 | 71 | 72 | //我们要实现的结构是一个树形结构 73 | /* 74 | -文件夹-rootFolder 75 | -Swift文件 76 | —Ojbc文件 77 | -子文件夹-SubFolder 78 | -Swift文件 79 | —Ojbc文件 80 | */ 81 | 82 | //创建根文件夹 83 | let rootFolder: FileType = Folder(folderName: "根文件夹") 84 | let objcFile1: FileType = ObjCFile(fileName: "objc1.h") 85 | let swiftFile1: FileType = SwiftFile(fileName: "file1.Swift") 86 | rootFolder.addFile(swiftFile1) 87 | rootFolder.addFile(objcFile1) 88 | 89 | let subFolder : FileType = Folder(folderName: "子文件夹") 90 | let objcFile2: FileType = ObjCFile(fileName: "objc2.h") 91 | let swiftFile2: FileType = SwiftFile(fileName: "file2.Swift") 92 | subFolder.addFile(swiftFile2) 93 | subFolder.addFile(objcFile2) 94 | 95 | rootFolder.addFile(subFolder) 96 | 97 | //输出该目录下的所有文件夹和文件名 98 | rootFolder.display() 99 | -------------------------------------------------------------------------------- /组合模式-Composite Pattern/类图/E7554EE6-D9AA-4F3A-B85D-EFF7637C9256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/组合模式-Composite Pattern/类图/E7554EE6-D9AA-4F3A-B85D-EFF7637C9256.png -------------------------------------------------------------------------------- /装饰者模式-Decorator Pattern/代码/Coffee.swift: -------------------------------------------------------------------------------- 1 | //====装饰者模式(Decorate Pattern)==== 2 | //开放关闭原则:类应该对扩展开放,对修改关闭 3 | //在不修改代码的情况下进行功能扩展 4 | //装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰着提供了比继承更有弹性的替代方案。 5 | 6 | ///=================定义基类========================== 7 | /// 饮料基类 8 | class Beverage { 9 | var description: String 10 | 11 | init(description: String = "Unknown Beverage") { 12 | self.description = description 13 | } 14 | 15 | func getDescription() -> String { 16 | return description 17 | } 18 | 19 | func cost() -> Double { 20 | return 0.0 21 | } 22 | } 23 | 24 | /// 调料基类 25 | class CondimentDecorator: Beverage { 26 | override func getDescription() -> String { 27 | return "" 28 | } 29 | } 30 | 31 | 32 | 33 | ///=================实现不同的咖啡============== 34 | /// 浓缩咖啡 35 | class Espresso: Beverage { 36 | init() { 37 | super.init(description: "浓缩咖啡") 38 | } 39 | 40 | override func cost() -> Double { 41 | return 1.99 42 | } 43 | } 44 | 45 | class HouseBlend: Beverage { 46 | init() { 47 | super.init(description: "星巴克杜绝调配咖啡:综合咖啡") 48 | } 49 | 50 | override func cost() -> Double { 51 | return 0.99 52 | } 53 | } 54 | 55 | 56 | 57 | /// ============实现各种调料=========== 58 | ///摩卡 59 | class Mocha: CondimentDecorator { 60 | var beverage: Beverage 61 | init(beverage: Beverage) { 62 | self.beverage = beverage 63 | } 64 | 65 | override func getDescription() -> String { 66 | return "摩卡, " + beverage.getDescription() 67 | } 68 | 69 | override func cost() -> Double { 70 | return beverage.cost() + 0.29 71 | } 72 | } 73 | 74 | /// 牛奶 75 | class Milk: CondimentDecorator { 76 | var beverage: Beverage 77 | init(beverage: Beverage) { 78 | self.beverage = beverage 79 | } 80 | 81 | override func getDescription() -> String { 82 | return "牛奶, " + beverage.getDescription() 83 | } 84 | 85 | override func cost() -> Double { 86 | return beverage.cost() + 0.59 87 | } 88 | } 89 | 90 | 91 | 92 | /** 93 | * 使用 94 | */ 95 | //创建浓缩咖啡 96 | var espresso: Beverage = Espresso() 97 | 98 | /** 99 | * 用户点了一杯牛奶摩卡浓缩咖啡 100 | */ 101 | espresso = Milk(beverage: espresso) //加牛奶 102 | espresso = Mocha(beverage: espresso) //加Mocha 103 | 104 | espresso.getDescription() 105 | espresso.cost() 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /装饰者模式-Decorator Pattern/代码/Flower.swift: -------------------------------------------------------------------------------- 1 | /// 花瓶的基类 2 | class VaseComponent { 3 | 4 | private var description: String //对花瓶进行描述 5 | 6 | init(description: String = "花瓶") { 7 | self.description = description 8 | } 9 | 10 | func getDescription() -> String { 11 | return self.description 12 | } 13 | 14 | func display() { 15 | print(getDescription()) //打印描述信息 16 | } 17 | } 18 | 19 | 20 | /// 鲜花的父类,因为装饰者就是最新的花瓶组件,所以要继承自VaseComponent 21 | class FlowerDecorator: VaseComponent { 22 | var vase: VaseComponent 23 | 24 | init(vase: VaseComponent) { 25 | self.vase = vase 26 | } 27 | } 28 | 29 | 30 | /// 创建特定的花瓶 31 | class Porcelain: VaseComponent { 32 | init() { 33 | super.init(description: "瓷花瓶:") 34 | } 35 | } 36 | 37 | class Glass: VaseComponent { 38 | init() { 39 | super.init(description: "玻璃花瓶:") 40 | } 41 | } 42 | 43 | 44 | 45 | //往花瓶里加入特定的化进行装饰 46 | /// 玫瑰花 47 | class Rose: FlowerDecorator{ 48 | override func getDescription() -> String { 49 | return vase.getDescription() + "玫瑰 " 50 | } 51 | } 52 | 53 | //百合花 54 | class Lily: FlowerDecorator { 55 | override func getDescription() -> String { 56 | return vase.getDescription() + "百合 " 57 | } 58 | } 59 | 60 | var porcelain: VaseComponent = Porcelain() //创建空花瓶 61 | porcelain.display() //打印最新的描述信息 62 | 63 | porcelain = Rose(vase: porcelain) //插入玫瑰 64 | porcelain = Lily(vase: porcelain) //插入百合 65 | 66 | porcelain.display() //打印最新的描述信息 67 | 68 | 69 | 70 | //var glass: VaseComponent = Glass() 71 | //glass = Lily(vase: glass) 72 | //glass.display() 73 | // 74 | -------------------------------------------------------------------------------- /装饰者模式-Decorator Pattern/类图/CFAD9C6B-41C1-4A4E-BFB0-B5CA4D300959.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/装饰者模式-Decorator Pattern/类图/CFAD9C6B-41C1-4A4E-BFB0-B5CA4D300959.png -------------------------------------------------------------------------------- /装饰者模式-Decorator Pattern/类图/屏幕快照 2016-04-05 下午4.16.50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/装饰者模式-Decorator Pattern/类图/屏幕快照 2016-04-05 下午4.16.50.png -------------------------------------------------------------------------------- /装饰者模式-Decorator Pattern/类图/屏幕快照 2016-04-05 下午5.16.17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/装饰者模式-Decorator Pattern/类图/屏幕快照 2016-04-05 下午5.16.17.png -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/BCF7A2A0-0384-44E6-9411-0E9275132BAA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/观察者模式-Observer Pattern/BCF7A2A0-0384-44E6-9411-0E9275132BAA.png -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/MyCustomNotificationCenter.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MyCustomNotificationCenter.swift 3 | // DesignPatternDemo 4 | // 5 | // Created by Mr.LuDashi on 16/3/22. 6 | // Copyright © 2016年 ZeluLi. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | ///通知 12 | class MyCustomNotification : NSObject { 13 | let name: String 14 | let object: AnyObject? 15 | let userInfo: [NSObject : AnyObject]? 16 | 17 | init(name: String, object: AnyObject?, userInfo: [NSObject : AnyObject]?){ 18 | self.name = name 19 | self.object = object 20 | self.userInfo = userInfo 21 | } 22 | } 23 | 24 | 25 | //观察者 26 | class MyObserver: NSObject { 27 | let observer: AnyObject 28 | let selector: Selector 29 | 30 | init(observer: AnyObject, selector: Selector) { 31 | self.observer = observer 32 | self.selector = selector 33 | } 34 | } 35 | 36 | typealias ObserverArray = Array 37 | //主题 38 | class MySubject: NSObject { 39 | var notification: MyCustomNotification? 40 | var observers: ObserverArray 41 | 42 | init(notification: MyCustomNotification!, observers: ObserverArray) { 43 | self.notification = notification 44 | self.observers = observers 45 | } 46 | 47 | //添加观察者 48 | func addCustomObserver(observe: MyObserver) { 49 | for var i = 0; i < observers.count; i++ { 50 | if observers[i].observer === observe.observer { 51 | return 52 | } 53 | } 54 | self.observers.append(observe) 55 | } 56 | 57 | //移除观察者 58 | func removeCustomObserver(observe: AnyObject) { 59 | for var i = 0; i < observers.count; i++ { 60 | if observers[i].observer === observe { 61 | observers.removeAtIndex(i); 62 | break; 63 | } 64 | } 65 | } 66 | 67 | //发送通知 68 | func postNotification() { 69 | for var i = 0; i < observers.count; i++ { 70 | let myObserver: MyObserver = self.observers[i] 71 | myObserver.observer.performSelector(myObserver.selector, withObject: self.notification) 72 | } 73 | } 74 | } 75 | 76 | 77 | 78 | 79 | typealias SubjectDictionary = Dictionary 80 | 81 | class MyCustomNotificationCenter: NSObject { 82 | 83 | //================创建单例============================= 84 | private static let singleton = MyCustomNotificationCenter() 85 | static func defaultCenter() -> MyCustomNotificationCenter { 86 | return singleton 87 | } 88 | override private init() { 89 | super.init() 90 | } 91 | 92 | 93 | //================通知中心,存储的是Subject对象的集合============ 94 | private var center: SubjectDictionary = SubjectDictionary() 95 | 96 | //发出通知 97 | func postNotification(notification: MyCustomNotification) { 98 | 99 | let subject = self.getSubjectWithNotifaction(notification) 100 | subject.postNotification() 101 | 102 | } 103 | 104 | //根据Notification获取相应的Subject对象,没有的话就创建 105 | func getSubjectWithNotifaction(notification: MyCustomNotification) -> MySubject { 106 | 107 | guard let subject: MySubject = center[notification.name] else { 108 | center[notification.name] = MySubject(notification: notification, observers: ObserverArray()) 109 | return self.getSubjectWithNotifaction(notification) 110 | } 111 | 112 | if subject.notification == nil { 113 | subject.notification = notification 114 | } 115 | 116 | return subject 117 | } 118 | 119 | //添加监听者 120 | func addObserver(observer: AnyObject, aSelector: Selector, aName: String) { 121 | let myObserver = MyObserver(observer: observer, selector: aSelector) 122 | 123 | var subject: MySubject? = center[aName] 124 | 125 | if subject == nil { 126 | subject = MySubject(notification: nil, observers: ObserverArray()) 127 | center[aName] = subject 128 | } 129 | 130 | subject!.addCustomObserver(myObserver) 131 | } 132 | 133 | //从通知中心移除Observe 134 | func removeObserver(observer: AnyObject, name: String) { 135 | guard let subject: MySubject = center[name] else { 136 | return 137 | } 138 | subject.removeCustomObserver(observer) 139 | 140 | } 141 | 142 | } 143 | 144 | 145 | 146 | class Boss: NSObject { 147 | func sendMessage(message: String) { 148 | //1.创建消息字典 149 | let userInfo = ["message":message]; 150 | //2.创建通知 151 | let notifaction = MyCustomNotification.init(name: "Boss", object:self, userInfo: userInfo) 152 | //3.发送通知 153 | MyCustomNotificationCenter.defaultCenter().postNotification(notifaction) 154 | } 155 | 156 | } 157 | 158 | //通知的接受者 159 | class Coder: NSObject { 160 | func observeBoss() { 161 | MyCustomNotificationCenter.defaultCenter().addObserver(self, aSelector: "accepteNotificaton:", aName: "Boss") 162 | } 163 | 164 | func accepteNotificaton(notification: MyCustomNotification) { 165 | let info: Dictionary = notification.userInfo! 166 | print("收到老板的通知了:\(info["message"]!)") 167 | } 168 | 169 | deinit { 170 | MyCustomNotificationCenter.defaultCenter().removeObserver(self, name: "Boss") 171 | } 172 | } 173 | 174 | 175 | let boss = Boss() 176 | let coder = Coder() 177 | let coder1 = Coder() 178 | 179 | coder.observeBoss() 180 | coder1.observeBoss() 181 | 182 | boss.sendMessage("涨工资啦") 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/Notification.swift: -------------------------------------------------------------------------------- 1 | //使用Foundation中自带的通知模式 2 | 3 | //Subject 4 | class Boss: NSObject { 5 | func sendMessage(message: String) { 6 | //1.创建消息字典 7 | let userInfo = ["message":message]; 8 | //2.创建通知 9 | let notifaction = NSNotification.init(name: "Boss", object:self, userInfo: userInfo) 10 | //3.发送通知 11 | NSNotificationCenter.defaultCenter().postNotification(notifaction) 12 | } 13 | 14 | } 15 | 16 | //Observer 17 | class Coder: NSObject { 18 | func observeBoss() { 19 | NSNotificationCenter.defaultCenter().addObserver(self, selector:"accepteNotificaton:", name: "Boss", object: nil) 20 | } 21 | 22 | func accepteNotificaton(notification: NSNotification) { 23 | let info: Dictionary = notification.userInfo! 24 | print("收到老板的通知了:\(info["message"]!)") 25 | } 26 | 27 | deinit { 28 | NSNotificationCenter.defaultCenter().removeObserver(self, name: "Boss", object: nil) 29 | } 30 | } 31 | 32 | 33 | let boss = Boss() 34 | 35 | let coder = Coder() 36 | coder.observeBoss() 37 | 38 | boss.sendMessage("涨工资啦") 39 | -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/ObserverAndSubject.swift: -------------------------------------------------------------------------------- 1 | //==========观察者模式============================================= 2 | //设计原则:为了交互对象之间的松耦合设计而努力 3 | class ObserverType { 4 | var info: String = "" 5 | func update(info: String) {} 6 | func display(){} 7 | } 8 | 9 | class SubjectType { 10 | private var observersArray: Array = Array() 11 | private var info: String = "" 12 | func registerObserver(observer: ObserverType){} 13 | func removeObserver(observer: ObserverType){} 14 | func notifyObservers(){} 15 | } 16 | 17 | 18 | //发出通知的人,也就是通知中心,大Boss 19 | class Boss: SubjectType { 20 | 21 | func setInfo(info: String) { 22 | if info != self.info { 23 | self.info = info 24 | self.notifyObservers() 25 | } 26 | } 27 | 28 | override func registerObserver(observer: ObserverType) { 29 | self.removeObserver(observer) 30 | self.observersArray.append(observer) 31 | } 32 | 33 | override func removeObserver(observer: ObserverType) { 34 | for var i = 0; i < self.observersArray.count; i++ { 35 | if observersArray[i] === observer { 36 | self.observersArray.removeAtIndex(i); 37 | break 38 | } 39 | } 40 | } 41 | 42 | override func notifyObservers() { 43 | for observer:ObserverType in self.observersArray { 44 | observer.update(self.info) 45 | } 46 | } 47 | } 48 | 49 | 50 | //程序员 51 | class Coder: ObserverType { 52 | 53 | override func update(info: String) { 54 | self.info = info 55 | display() 56 | } 57 | 58 | override func display() { 59 | print("程序员收到:\(self.info)") 60 | } 61 | } 62 | 63 | //产品经理 64 | class PM: ObserverType { 65 | 66 | override func update(info: String) { 67 | self.info = info 68 | display() 69 | } 70 | 71 | override func display() { 72 | print("产品经理收到收到:\(self.info)") 73 | } 74 | } 75 | 76 | 77 | //创建Boss 78 | let bossSubject: Boss = Boss() 79 | 80 | //创建观察者 81 | let coderObserver: Coder = Coder() 82 | let pmObserver: PM = PM() 83 | 84 | //添加观察着 85 | bossSubject.registerObserver(coderObserver) 86 | bossSubject.registerObserver(pmObserver) 87 | bossSubject.setInfo("第一次通知") 88 | 89 | //程序员走出了会议室(移除观察者) 90 | bossSubject.removeObserver(coderObserver) 91 | bossSubject.setInfo("第二次通知") 92 | -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/屏幕快照 2016-03-23 上午10.25.34.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/观察者模式-Observer Pattern/屏幕快照 2016-03-23 上午10.25.34.png -------------------------------------------------------------------------------- /观察者模式-Observer Pattern/屏幕快照 2016-03-23 下午3.26.31.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/观察者模式-Observer Pattern/屏幕快照 2016-03-23 下午3.26.31.png -------------------------------------------------------------------------------- /迭代器模式-Iterator Pattern/代码/无“迭代器模式”.swift: -------------------------------------------------------------------------------- 1 | protocol CinemaType01 { 2 | func display() 3 | } 4 | 5 | class Cinema01: CinemaType01 { 6 | private let items = ["美人鱼", "夏洛特烦恼", "末日崩塌"] 7 | func display() { 8 | print("\n第一电影院:") 9 | for i in 0.. = Array() 33 | 34 | func addCinema(cinema: CinemaType01) { 35 | self.cinemas.append(cinema) 36 | } 37 | 38 | func display() { 39 | for i in 0.. Bool 4 | func next() -> AnyObject? 5 | } 6 | 7 | class ArrayIterator: Iterator { 8 | private let items: Array 9 | private var position: Int = 0 10 | 11 | init(items: Array) { 12 | self.items = items 13 | } 14 | 15 | func hasNext() -> Bool { 16 | return position < items.count 17 | } 18 | 19 | func next() -> AnyObject? { 20 | let item = items[position] 21 | position += 1 22 | return item 23 | } 24 | } 25 | 26 | class DictionaryIterator: Iterator { 27 | 28 | private let items: Dictionary 29 | private var position: Int = 0 30 | private var allKeys: [String] { 31 | get{ 32 | return Array(items.keys) 33 | } 34 | } 35 | 36 | init(items: Dictionary) { 37 | self.items = items 38 | } 39 | 40 | func hasNext() -> Bool { 41 | return position < items.count 42 | } 43 | 44 | func next() -> AnyObject? { 45 | let item = items[allKeys[position]] 46 | position += 1 47 | return item 48 | } 49 | } 50 | 51 | 52 | 53 | 54 | protocol CinemaType { 55 | func createIterator() -> Iterator 56 | func iteratorItem() 57 | } 58 | 59 | extension CinemaType { 60 | func iteratorItem() { 61 | let iterator = createIterator() 62 | while iterator.hasNext() { 63 | guard let item = iterator.next() else { 64 | continue 65 | } 66 | print(item) 67 | } 68 | } 69 | } 70 | 71 | 72 | class Cinema01: CinemaType { 73 | let items = ["美人鱼", "夏洛特烦恼", "末日崩塌"] 74 | func createIterator() -> Iterator { 75 | return ArrayIterator(items: items) 76 | } 77 | } 78 | 79 | class Cinema02: CinemaType { 80 | let items = ["001": "老炮儿", "002": "疯狂动物城", "003": "泰囧"] 81 | func createIterator() -> Iterator { 82 | return DictionaryIterator(items: items) 83 | } 84 | } 85 | 86 | class Market { 87 | private var cinemas: Array = Array() 88 | 89 | func addCinema(cinema: CinemaType) { 90 | self.cinemas.append(cinema) 91 | } 92 | 93 | func display() { 94 | for i in 0.. Float 4 | } 5 | 6 | ///家用插座输出电压为220V 7 | class Socket: SocketType { 8 | func socketOutputVoltage() -> Float { 9 | return 220.0 10 | } 11 | } 12 | 13 | 14 | //========计算机电源接口================ 15 | protocol ComputerPowerSourceType { 16 | func outputVoltage() -> Float 17 | } 18 | 19 | //MacBookPro的电池(自带电源) 20 | class MacBookProBattery: ComputerPowerSourceType{ 21 | func outputVoltage() -> Float { 22 | return 16.5 23 | } 24 | } 25 | 26 | class MacBookPro { 27 | //电源 28 | private var powerSource: ComputerPowerSourceType? = nil 29 | 30 | //连接电源 31 | func connectPowerSource(powerSource: ComputerPowerSourceType) { 32 | self.powerSource = powerSource 33 | } 34 | 35 | //电源输入电压 36 | func inputVoltage() { 37 | if powerSource != nil { 38 | print("输入电压为:\(powerSource!.outputVoltage())") 39 | } 40 | } 41 | } 42 | 43 | //如果没有适配器,MacBookPro就只能使用MacBookProBattery(自带电池),而无法使用Socket(插座),要想MacBookPro也可以使用Socket进行供电就必须有“适配器”进行转换 44 | 45 | 46 | 47 | //计算机连接插座的适配器 48 | 49 | //对象适配器:包含某个插座类型 50 | class MacPowerObjectAdapter: ComputerPowerSourceType { 51 | var socketPower: SocketType? = nil //电源接口对象 52 | 53 | //适配器的一端插入插座 54 | func insertSocket(socketPower: SocketType) { 55 | self.socketPower = socketPower 56 | } 57 | 58 | //电流通过适配器后进行输出,输出规则要遵循ComputerPowerSourceType协议 59 | func outputVoltage() -> Float { 60 | //通过各种电路将电压进行转换 61 | guard let voltage = socketPower?.socketOutputVoltage() else { 62 | return 0 63 | } 64 | 65 | if voltage > 16.5 { 66 | return 16.5 67 | } else { 68 | return 0 69 | } 70 | } 71 | } 72 | 73 | //类适配器:继承自某个特定插座并实现计算机电源协议 74 | class MacPowerClassAdapter: Socket, ComputerPowerSourceType { 75 | func outputVoltage() -> Float { 76 | if self.socketOutputVoltage() > 16.5 { 77 | return 16.5 78 | } else { 79 | return 0 80 | } 81 | } 82 | } 83 | 84 | 85 | 86 | let macBookPro: MacBookPro = MacBookPro() //创建笔记本对象 87 | let macBookProBattery = MacBookProBattery() //创建MacBookPro所用电池的对象 88 | let socket: SocketType = Socket() //创建电源对象 89 | 90 | //创建适配器“对象适配器”的对象 91 | let macBookProObjectAdapter: MacPowerObjectAdapter = MacPowerObjectAdapter() 92 | 93 | //创建“类适配器”对象 94 | let macBookProClassAdapter: MacPowerClassAdapter = MacPowerClassAdapter() 95 | 96 | 97 | print("笔记本使用电池") 98 | macBookPro.connectPowerSource(macBookProBattery) 99 | macBookPro.inputVoltage() 100 | 101 | print("\n电池没电了,使用对象适配器") 102 | macBookProObjectAdapter.insertSocket(socket) //1.适配器插入插座 103 | macBookPro.connectPowerSource(macBookProObjectAdapter) //2.MacBookPro连接适配器 104 | macBookPro.inputVoltage() //3.电流输出 105 | 106 | print("\n使用类适配器") 107 | macBookPro.connectPowerSource(macBookProClassAdapter) 108 | macBookPro.inputVoltage() -------------------------------------------------------------------------------- /适配器模式-Adapter Pattern/代码/Demo1.swift: -------------------------------------------------------------------------------- 1 | protocol AType { 2 | func functionA(); 3 | } 4 | 5 | class A: AType { 6 | func functionA() { 7 | print("我是AAA") 8 | } 9 | } 10 | 11 | 12 | protocol BType { 13 | func functionB() 14 | } 15 | 16 | class B: BType { 17 | func functionB() { 18 | print("我是BBBB") 19 | } 20 | } 21 | 22 | 23 | //对象适配器 24 | class AdapterA: BType { 25 | var a: AType 26 | init(a: AType) { 27 | self.a = a 28 | } 29 | 30 | func functionB() { 31 | a.functionA() 32 | } 33 | } 34 | 35 | //类适配器 36 | class AdapterAA: A, BType{ 37 | func functionB() { 38 | self.functionA() 39 | } 40 | } 41 | 42 | 43 | func driverB(b: BType) { 44 | b.functionB() 45 | } 46 | -------------------------------------------------------------------------------- /适配器模式-Adapter Pattern/适配器类图.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lizelu/DesignPatterns-Swift/f21e32d89fbf917a612903f9bc337d30036c89f4/适配器模式-Adapter Pattern/适配器类图.png --------------------------------------------------------------------------------