Showing preview only (261K chars total). Download the full file or copy to clipboard to get everything.
Repository: ochococo/Design-Patterns-In-Swift
Branch: master
Commit: 81264fefaaf0
Files: 99
Total size: 237.5 KB
Directory structure:
gitextract_rec1cm42/
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── generate-playground.yml
├── .gitignore
├── CONTRIBUTING-CN.md
├── CONTRIBUTING.md
├── Design-Patterns-CN.playground/
│ ├── Pages/
│ │ ├── Behavioral.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Creational.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Index.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ └── Structural.xcplaygroundpage/
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
│ └── contents.xcplayground
├── Design-Patterns.playground/
│ ├── Pages/
│ │ ├── Behavioral.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Creational.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Index.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ └── Structural.xcplaygroundpage/
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
│ └── contents.xcplayground
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README-CN.md
├── README.md
├── generate-playground-cn.sh
├── generate-playground.sh
├── source/
│ ├── Index/
│ │ ├── header.md
│ │ └── welcome.swift
│ ├── behavioral/
│ │ ├── chain_of_responsibility.swift
│ │ ├── command.swift
│ │ ├── header.md
│ │ ├── interpreter.swift
│ │ ├── iterator.swift
│ │ ├── mediator.swift
│ │ ├── memento.swift
│ │ ├── observer.swift
│ │ ├── state.swift
│ │ ├── strategy.swift
│ │ ├── template_method.swift
│ │ └── visitor.swift
│ ├── contents.md
│ ├── contentsReadme.md
│ ├── creational/
│ │ ├── abstract_factory.swift
│ │ ├── builder.swift
│ │ ├── factory.swift
│ │ ├── header.md
│ │ ├── monostate.swift
│ │ ├── prototype.swift
│ │ └── singleton.swift
│ ├── endComment
│ ├── endSwiftCode
│ ├── footer.md
│ ├── imports.swift
│ ├── startComment
│ ├── startSwiftCode
│ └── structural/
│ ├── adapter.swift
│ ├── bridge.swift
│ ├── composite.swift
│ ├── decorator.swift
│ ├── facade.swift
│ ├── flyweight.swift
│ ├── header.md
│ ├── protection_proxy.swift
│ └── virtual_proxy.swift
└── source-cn/
├── Index/
│ ├── header.md
│ └── welcome.swift
├── behavioral/
│ ├── chain_of_responsibility.swift
│ ├── command.swift
│ ├── header.md
│ ├── interpreter.swift
│ ├── iterator.swift
│ ├── mediator.swift
│ ├── memento.swift
│ ├── observer.swift
│ ├── state.swift
│ ├── strategy.swift
│ ├── template_method.swift
│ └── visitor.swift
├── contents.md
├── contentsReadme.md
├── creational/
│ ├── abstract_factory.swift
│ ├── builder.swift
│ ├── factory.swift
│ ├── header.md
│ ├── monostate.swift
│ ├── prototype.swift
│ └── singleton.swift
├── endComment
├── endSwiftCode
├── footer.md
├── imports.swift
├── startComment
├── startSwiftCode
└── structural/
├── adapter.swift
├── bridge.swift
├── composite.swift
├── decorator.swift
├── facade.swift
├── flyweight.swift
├── header.md
├── protection_proxy.swift
└── virtual_proxy.swift
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: ochococo
================================================
FILE: .github/workflows/generate-playground.yml
================================================
name: Generate Playground Files and READMES
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
push:
branches: [master]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
generate-playgrounds:
# The type of runner that the job will run on
runs-on: macos-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
# Checkout & Generate
- name: Generate playgrounds and readmes
run: |
./generate-playground.sh
./generate-playground-cn.sh
# Commit
- name: Commit files
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add Design-Patterns-CN.playground.zip
git add Design-Patterns.playground.zip
git add README.md
git add README-CN.md
git commit -m "Generate Playground"
## Push changes to master branch
- name: Push changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: "master"
force: false
# This workflow contains a single job called "build"
generate-chinese-branch:
needs: generate-playgrounds
# The type of runner that the job will run on
runs-on: macos-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
# Checkout & Generate
- name: Generate Chinese Readme
run: |
./generate-playground-cn.sh
mv ./README-CN.md ./README.md
# Commit
- name: Commit files
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add README.md
git commit -m "Generate Chinese version"
## Push changes to chinese branch
- name: Push changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: "chinese"
force: true
================================================
FILE: .gitignore
================================================
.DS_Store
UserInterfaceState.xcuserstate
playground.xcworkspace
xcuserdata
================================================
FILE: CONTRIBUTING-CN.md
================================================
如何贡献(中文版)?
==================
- 你很棒!
- 仅建议编辑`source-cn`目录中的文件,其余内容是自动生成的并已翻译
- 提交更改
- 本地运行`generate-playground-cn.sh`
- 本地打开`Design-Patterns-CN.playground`文件并检查是否正常运行
- 删除`generate-playground.sh`引起的更改,不要提交它!(_这是最近的更改_)
- 请耐心尊重其他贡献者
分支说明
==================
英文原上游主仓库已与中文版[统一维护](https://github.com/ochococo/Design-Patterns-In-Swift/pull/93):
- master 为主维护分支
- chinese 分支仅为方便展示,将 README.md 显示为中文版本,由 GitHub Action 自动驱动
因此,直接将 PR 提交至[原始仓库](https://github.com/ochococo/Design-Patterns-In-Swift) master 主分支即可。
================================================
FILE: CONTRIBUTING.md
================================================
How to contribute?
==================
- You are awesome!
- Only editing files inside `source` is recommended, the rest is autogenerated and translated
- Commit changes
- Run `generate-playground.sh` locally
- Open the .playground locally and check if it works
- Remove the changes caused by `generate-playground.sh`, do not commit it! (_THIS IS A RECENT CHANGE_)
- Please be patient and respectful to fellow contributors
================================================
FILE: Design-Patterns-CN.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
================================================
/*:
行为型模式
========
>在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
/*:
🐝 责任链(Chain Of Responsibility)
------------------------------
责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。
### 示例:
*/
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next = self.next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
/*:
### 用法
*/
// 创建一系列的钱堆,并将其链接起来:10<20<50<100
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// 创建 ATM 实例
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
/*:
👫 命令(Command)
------------
命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
* 重复多次
* 取消(如果该对象有实现的话)
* 取消后又再重做
### 示例:
*/
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### 用法
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
/*:
🎶 解释器(Interpreter)
------------------
给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
### 示例:
*/
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
/*:
### 用法
*/
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
/*:
🍫 迭代器(Iterator)
---------------
迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
### 示例:
*/
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
/*:
### 用法
*/
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
/*:
💐 中介者(Mediator)
---------------
用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。
### 示例:
*/
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
/*:
### 用法
*/
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
/*:
💾 备忘录(Memento)
--------------
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
### 示例:
*/
typealias Memento = [String: String]
/*:
发起人(Originator)
*/
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
/*:
管理者(Caretaker)
*/
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
/*:
### 用法
*/
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
/*:
👓 观察者(Observer)
---------------
一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知
### 示例:
*/
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
/*:
### 用法
*/
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
/*:
🐉 状态(State)
---------
在状态模式中,对象的行为是基于它的内部状态而改变的。
这个模式允许某个类对象在运行时发生改变。
### 示例:
*/
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
/*:
### 用法
*/
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
/*:
💡 策略(Strategy)
--------------
对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
* 定义了一族算法(业务规则);
* 封装了每个算法;
* 这族的算法可互换代替(interchangeable)。
### 示例:
*/
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
/*:
### 用法
*/
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
/*:
📝 模板方法模式
-----------
模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。
### 示例:
*/
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
/*:
### 用法
*/
let roseGarden = RoseGarden()
roseGarden.prepare()
/*:
🏃 访问者(Visitor)
--------------
封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
### 示例:
*/
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
/*:
### 用法
*/
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
================================================
FILE: Design-Patterns-CN.playground/Pages/Creational.xcplaygroundpage/Contents.swift
================================================
/*:
创建型模式
========
> 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
/*:
🌰 抽象工厂(Abstract Factory)
-------------
抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。
### 示例:
协议
*/
protocol BurgerDescribing {
var ingredients: [String] { get }
}
struct CheeseBurger: BurgerDescribing {
let ingredients: [String]
}
protocol BurgerMaking {
func make() -> BurgerDescribing
}
// 工厂方法实现
final class BigKahunaBurger: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
}
}
final class JackInTheBox: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
}
}
/*:
抽象工厂
*/
enum BurgerFactoryType: BurgerMaking {
case bigKahuna
case jackInTheBox
func make() -> BurgerDescribing {
switch self {
case .bigKahuna:
return BigKahunaBurger().make()
case .jackInTheBox:
return JackInTheBox().make()
}
}
}
/*:
### 用法
*/
let bigKahuna = BurgerFactoryType.bigKahuna.make()
let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
/*:
👷 生成器(Builder)
--------------
一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
### 示例:
*/
final class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
/*:
### 用法
*/
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
/*:
🏭 工厂方法(Factory Method)
-----------------------
定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
### 示例:
*/
protocol CurrencyDescribing {
var symbol: String { get }
var code: String { get }
}
final class Euro: CurrencyDescribing {
var symbol: String {
return "€"
}
var code: String {
return "EUR"
}
}
final class UnitedStatesDolar: CurrencyDescribing {
var symbol: String {
return "$"
}
var code: String {
return "USD"
}
}
enum Country {
case unitedStates
case spain
case uk
case greece
}
enum CurrencyFactory {
static func currency(for country: Country) -> CurrencyDescribing? {
switch country {
case .spain, .greece:
return Euro()
case .unitedStates:
return UnitedStatesDolar()
default:
return nil
}
}
}
/*:
### 用法
*/
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
/*:
🔂 单态(Monostate)
------------
单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。
因此,在这种情况下,单态会将状态保存为静态,而不是将整个实例保存为单例。
[单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
### 示例:
*/
class Settings {
enum Theme {
case `default`
case old
case new
}
private static var theme: Theme?
var currentTheme: Theme {
get { Settings.theme ?? .default }
set(newTheme) { Settings.theme = newTheme }
}
}
/*:
### 用法:
*/
import SwiftUI
// 改变主题
let settings = Settings() // 开始使用主题 .old
settings.currentTheme = .new // 改变主题为 .new
// 界面一
let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
// 界面二
let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
/*:
🃏 原型(Prototype)
--------------
通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
### 示例:
*/
class MoonWorker {
let name: String
var health: Int = 100
init(name: String) {
self.name = name
}
func clone() -> MoonWorker {
return MoonWorker(name: name)
}
}
/*:
### 用法
*/
let prototype = MoonWorker(name: "Sam Bell")
var bell1 = prototype.clone()
bell1.health = 12
var bell2 = prototype.clone()
bell2.health = 23
var bell3 = prototype.clone()
bell3.health = 0
/*:
💍 单例(Singleton)
--------------
单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为
### 示例:
*/
final class ElonMusk {
static let shared = ElonMusk()
private init() {
// Private initialization to ensure just one instance is created.
}
}
/*:
### 用法
*/
let elon = ElonMusk.shared // There is only one Elon Musk folks.
================================================
FILE: Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift
================================================
/*:
设计模式(Swift 5.0 实现)
======================
([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).
👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。
🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
print("您好!")
================================================
FILE: Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/Contents.swift
================================================
/*:
结构型模式(Structural)
====================
> 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
/*:
🔌 适配器(Adapter)
--------------
适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
### 示例:
*/
protocol NewDeathStarSuperLaserAiming {
var angleV: Double { get }
var angleH: Double { get }
}
/*:
**被适配者**
*/
struct OldDeathStarSuperlaserTarget {
let angleHorizontal: Float
let angleVertical: Float
init(angleHorizontal: Float, angleVertical: Float) {
self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}
}
/*:
**适配器**
*/
struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
private let target: OldDeathStarSuperlaserTarget
var angleV: Double {
return Double(target.angleVertical)
}
var angleH: Double {
return Double(target.angleHorizontal)
}
init(_ target: OldDeathStarSuperlaserTarget) {
self.target = target
}
}
/*:
### 用法
*/
let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
let newFormat = NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV
/*:
🌉 桥接(Bridge)
-----------
桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
### 示例:
*/
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
/*:
### 用法
*/
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()
/*:
🌿 组合(Composite)
--------------
将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
### 示例:
组件(Component)
*/
protocol Shape {
func draw(fillColor: String)
}
/*:
叶子节点(Leafs)
*/
final class Square: Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle: Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
/*:
组合
*/
final class Whiteboard: Shape {
private lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
/*:
### 用法
*/
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")
/*:
🍧 修饰(Decorator)
--------------
修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。
就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。
### 示例:
*/
protocol CostHaving {
var cost: Double { get }
}
protocol IngredientsHaving {
var ingredients: [String] { get }
}
typealias BeverageDataHaving = CostHaving & IngredientsHaving
struct SimpleCoffee: BeverageDataHaving {
let cost: Double = 1.0
let ingredients = ["Water", "Coffee"]
}
protocol BeverageHaving: BeverageDataHaving {
var beverage: BeverageDataHaving { get }
}
struct Milk: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Milk"]
}
}
struct WhipCoffee: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Whip"]
}
}
/*:
### 用法
*/
var someCoffee: BeverageDataHaving = SimpleCoffee()
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = Milk(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = WhipCoffee(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
/*:
🎁 外观(Facade)
-----------
外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
### 示例:
*/
final class Defaults {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
subscript(key: String) -> String? {
get {
return defaults.string(forKey: key)
}
set {
defaults.set(newValue, forKey: key)
}
}
}
/*:
### 用法
*/
let storage = Defaults()
// Store
storage["Bishop"] = "Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]
/*:
🍃 享元(Flyweight)
--------------
使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。
### 示例:
*/
// 特指咖啡生成的对象会是享元
struct SpecialityCoffee {
let origin: String
}
protocol CoffeeSearching {
func search(origin: String) -> SpecialityCoffee?
}
// 菜单充当特制咖啡享元对象的工厂和缓存
final class Menu: CoffeeSearching {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func search(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private let menu: CoffeeSearching
init(menu: CoffeeSearching) {
self.menu = menu
}
func takeOrder(origin: String, table: Int) {
orders[table] = menu.search(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
/*:
### 用法
*/
let coffeeShop = CoffeeShop(menu: Menu())
coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
coffeeShop.serve()
/*:
☔ 保护代理模式(Protection Proxy)
------------------
在代理模式中,创建一个类代表另一个底层类的功能。
保护代理用于限制访问。
### 示例:
*/
protocol DoorOpening {
func open(doors: String) -> String
}
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "pass" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
/*:
### 用法
*/
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password: "pass")
computer.open(doors: podBay)
/*:
🍬 虚拟代理(Virtual Proxy)
----------------
在代理模式中,创建一个类代表另一个底层类的功能。
虚拟代理用于对象的需时加载。
### 示例:
*/
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
/*:
### 用法
*/
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()
================================================
FILE: Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline
================================================
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
================================================
FILE: Design-Patterns-CN.playground/contents.xcplayground
================================================
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='6.0' target-platform='ios' display-mode='rendered'>
<pages>
<page name='Index'/>
<page name='Behavioral'/>
<page name='Creational'/>
<page name='Structural'/>
</pages>
</playground>
================================================
FILE: Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
================================================
/*:
Behavioral
==========
>In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
## Table of Contents
* [Behavioral](Behavioral)
* [Creational](Creational)
* [Structural](Structural)
*/
import Foundation
/*:
🐝 Chain Of Responsibility
--------------------------
The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
### Example:
*/
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next = self.next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
/*:
### Usage
*/
// Create piles of money and link them together 10 < 20 < 50 < 100.**
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// Build ATM.
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
/*:
👫 Command
----------
The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
### Example:
*/
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### Usage:
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
/*:
🎶 Interpreter
--------------
The interpreter pattern is used to evaluate sentences in a language.
### Example
*/
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
/*:
### Usage
*/
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
/*:
🍫 Iterator
-----------
The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
### Example:
*/
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
/*:
### Usage
*/
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
/*:
💐 Mediator
-----------
The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
### Example
*/
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
/*:
### Usage
*/
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
/*:
💾 Memento
----------
The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
### Example
*/
typealias Memento = [String: String]
/*:
Originator
*/
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
/*:
Caretaker
*/
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
/*:
### Usage
*/
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
/*:
👓 Observer
-----------
The observer pattern is used to allow an object to publish changes to its state.
Other objects subscribe to be immediately notified of any changes.
### Example
*/
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
/*:
### Usage
*/
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
/*:
🐉 State
---------
The state pattern is used to alter the behaviour of an object as its internal state changes.
The pattern allows the class for an object to apparently change at run-time.
### Example
*/
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
/*:
### Usage
*/
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
/*:
💡 Strategy
-----------
The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
### Example
*/
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
/*:
### Usage
*/
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
/*:
📝 Template Method
-----------
The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.
### Example
*/
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
/*:
### Usage
*/
let roseGarden = RoseGarden()
roseGarden.prepare()
/*:
🏃 Visitor
----------
The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
### Example
*/
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
/*:
### Usage
*/
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
================================================
FILE: Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift
================================================
/*:
Creational
==========
> In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
## Table of Contents
* [Behavioral](Behavioral)
* [Creational](Creational)
* [Structural](Structural)
*/
import Foundation
/*:
🌰 Abstract Factory
-------------------
The abstract factory pattern is used to provide a client with a set of related or dependant objects.
The "family" of objects created by the factory are determined at run-time.
### Example
Protocols
*/
protocol BurgerDescribing {
var ingredients: [String] { get }
}
struct CheeseBurger: BurgerDescribing {
let ingredients: [String]
}
protocol BurgerMaking {
func make() -> BurgerDescribing
}
// Number implementations with factory methods
final class BigKahunaBurger: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
}
}
final class JackInTheBox: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
}
}
/*:
Abstract factory
*/
enum BurgerFactoryType: BurgerMaking {
case bigKahuna
case jackInTheBox
func make() -> BurgerDescribing {
switch self {
case .bigKahuna:
return BigKahunaBurger().make()
case .jackInTheBox:
return JackInTheBox().make()
}
}
}
/*:
### Usage
*/
let bigKahuna = BurgerFactoryType.bigKahuna.make()
let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
/*:
👷 Builder
----------
The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm.
An external class controls the construction algorithm.
### Example
*/
final class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
/*:
### Usage
*/
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
/*:
🏭 Factory Method
-----------------
The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
### Example
*/
protocol CurrencyDescribing {
var symbol: String { get }
var code: String { get }
}
final class Euro: CurrencyDescribing {
var symbol: String {
return "€"
}
var code: String {
return "EUR"
}
}
final class UnitedStatesDolar: CurrencyDescribing {
var symbol: String {
return "$"
}
var code: String {
return "USD"
}
}
enum Country {
case unitedStates
case spain
case uk
case greece
}
enum CurrencyFactory {
static func currency(for country: Country) -> CurrencyDescribing? {
switch country {
case .spain, .greece:
return Euro()
case .unitedStates:
return UnitedStatesDolar()
default:
return nil
}
}
}
/*:
### Usage
*/
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
/*:
🔂 Monostate
------------
The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints.
So in that case, monostate saves the state as static instead of the entire instance as a singleton.
[SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
### Example:
*/
class Settings {
enum Theme {
case `default`
case old
case new
}
private static var theme: Theme?
var currentTheme: Theme {
get { Settings.theme ?? .default }
set(newTheme) { Settings.theme = newTheme }
}
}
/*:
### Usage:
*/
import SwiftUI
// When change the theme
let settings = Settings() // Starts using theme .old
settings.currentTheme = .new // Change theme to .new
// On screen 1
let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
// On screen 2
let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
/*:
🃏 Prototype
------------
The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
This practise is particularly useful when the construction of a new object is inefficient.
### Example
*/
class MoonWorker {
let name: String
var health: Int = 100
init(name: String) {
self.name = name
}
func clone() -> MoonWorker {
return MoonWorker(name: name)
}
}
/*:
### Usage
*/
let prototype = MoonWorker(name: "Sam Bell")
var bell1 = prototype.clone()
bell1.health = 12
var bell2 = prototype.clone()
bell2.health = 23
var bell3 = prototype.clone()
bell3.health = 0
/*:
💍 Singleton
------------
The singleton pattern ensures that only one object of a particular class is ever created.
All further references to objects of the singleton class refer to the same underlying instance.
There are very few applications, do not overuse this pattern!
### Example:
*/
final class ElonMusk {
static let shared = ElonMusk()
private init() {
// Private initialization to ensure just one instance is created.
}
}
/*:
### Usage:
*/
let elon = ElonMusk.shared // There is only one Elon Musk folks.
================================================
FILE: Design-Patterns.playground/Pages/Index.xcplaygroundpage/Contents.swift
================================================
/*:
Design Patterns implemented in Swift 5.0
========================================
A short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns.playground.zip)).
### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)
👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)
👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。
🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/GENERATE.md)
## Table of Contents
* [Behavioral](Behavioral)
* [Creational](Creational)
* [Structural](Structural)
*/
import Foundation
print("Welcome!")
================================================
FILE: Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift
================================================
/*:
Structural
==========
>In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)
## Table of Contents
* [Behavioral](Behavioral)
* [Creational](Creational)
* [Structural](Structural)
*/
import Foundation
/*:
🔌 Adapter
----------
The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
### Example
*/
protocol NewDeathStarSuperLaserAiming {
var angleV: Double { get }
var angleH: Double { get }
}
/*:
**Adaptee**
*/
struct OldDeathStarSuperlaserTarget {
let angleHorizontal: Float
let angleVertical: Float
init(angleHorizontal: Float, angleVertical: Float) {
self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}
}
/*:
**Adapter**
*/
struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
private let target: OldDeathStarSuperlaserTarget
var angleV: Double {
return Double(target.angleVertical)
}
var angleH: Double {
return Double(target.angleHorizontal)
}
init(_ target: OldDeathStarSuperlaserTarget) {
self.target = target
}
}
/*:
### Usage
*/
let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
let newFormat = NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV
/*:
🌉 Bridge
----------
The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
### Example
*/
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
/*:
### Usage
*/
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()
/*:
🌿 Composite
-------------
The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
### Example
Component
*/
protocol Shape {
func draw(fillColor: String)
}
/*:
Leafs
*/
final class Square: Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle: Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
/*:
Composite
*/
final class Whiteboard: Shape {
private lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
/*:
### Usage:
*/
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")
/*:
🍧 Decorator
------------
The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class.
This provides a flexible alternative to using inheritance to modify behaviour.
### Example
*/
protocol CostHaving {
var cost: Double { get }
}
protocol IngredientsHaving {
var ingredients: [String] { get }
}
typealias BeverageDataHaving = CostHaving & IngredientsHaving
struct SimpleCoffee: BeverageDataHaving {
let cost: Double = 1.0
let ingredients = ["Water", "Coffee"]
}
protocol BeverageHaving: BeverageDataHaving {
var beverage: BeverageDataHaving { get }
}
struct Milk: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Milk"]
}
}
struct WhipCoffee: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Whip"]
}
}
/*:
### Usage:
*/
var someCoffee: BeverageDataHaving = SimpleCoffee()
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = Milk(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = WhipCoffee(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
/*:
🎁 Façade
---------
The facade pattern is used to define a simplified interface to a more complex subsystem.
### Example
*/
final class Defaults {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
subscript(key: String) -> String? {
get {
return defaults.string(forKey: key)
}
set {
defaults.set(newValue, forKey: key)
}
}
}
/*:
### Usage
*/
let storage = Defaults()
// Store
storage["Bishop"] = "Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]
/*:
## 🍃 Flyweight
The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
### Example
*/
// Instances of SpecialityCoffee will be the Flyweights
struct SpecialityCoffee {
let origin: String
}
protocol CoffeeSearching {
func search(origin: String) -> SpecialityCoffee?
}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
final class Menu: CoffeeSearching {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func search(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private let menu: CoffeeSearching
init(menu: CoffeeSearching) {
self.menu = menu
}
func takeOrder(origin: String, table: Int) {
orders[table] = menu.search(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
/*:
### Usage
*/
let coffeeShop = CoffeeShop(menu: Menu())
coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
coffeeShop.serve()
/*:
☔ Protection Proxy
------------------
The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
Protection proxy is restricting access.
### Example
*/
protocol DoorOpening {
func open(doors: String) -> String
}
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "pass" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
/*:
### Usage
*/
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password: "pass")
computer.open(doors: podBay)
/*:
🍬 Virtual Proxy
----------------
The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
Virtual proxy is used for loading object on demand.
### Example
*/
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
/*:
### Usage
*/
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()
================================================
FILE: Design-Patterns.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline
================================================
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
================================================
FILE: Design-Patterns.playground/contents.xcplayground
================================================
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='6.0' target-platform='ios' display-mode='rendered'>
<pages>
<page name='Index'/>
<page name='Behavioral'/>
<page name='Creational'/>
<page name='Structural'/>
</pages>
</playground>
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: PULL_REQUEST_TEMPLATE.md
================================================
- [ ] Read [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md])
- [ ] Only edited files inside `source` folder (IMPORTANT) and commited them with a meaningful message
- [ ] Ran `generate-playground.sh`, no errors
- [ ] Opened playground, it worked fine
- [ ] Did not commit the changes caused by `generate-playground.sh`
- [ ] Linked to and/or created issue
- [ ] Added a description to PR
================================================
FILE: README-CN.md
================================================
设计模式(Swift 5.0 实现)
======================
([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).
👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。
🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。
🚀 如何由源代码,并生成 README 与 Playground 产物,请查看:
- [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)
- [CONTRIBUTING-CN.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING-CN.md)
```swift
print("您好!")
```
## 目录
| [行为型模式](#行为型模式) | [创建型模式](#创建型模式) | [结构型模式](#结构型模式structural) |
| ------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------------------ |
| [🐝 责任链 Chain Of Responsibility](#-责任链chain-of-responsibility) | [🌰 抽象工厂 Abstract Factory](#-抽象工厂abstract-factory) | [🔌 适配器 Adapter](#-适配器adapter) |
| [👫 命令 Command](#-命令command) | [👷 生成器 Builder](#-生成器builder) | [🌉 桥接 Bridge](#-桥接bridge) |
| [🎶 解释器 Interpreter](#-解释器interpreter) | [🏭 工厂方法 Factory Method](#-工厂方法factory-method) | [🌿 组合 Composite](#-组合composite) |
| [🍫 迭代器 Iterator](#-迭代器iterator) | [🔂 单态 Monostate](#-单态monostate) | [🍧 修饰 Decorator](#-修饰decorator) |
| [💐 中介者 Mediator](#-中介者mediator) | [🃏 原型 Prototype](#-原型prototype) | [🎁 外观 Façade](#-外观facade) |
| [💾 备忘录 Memento](#-备忘录memento) | [💍 单例 Singleton](#-单例singleton) | [🍃 享元 Flyweight](#-享元flyweight) |
| [👓 观察者 Observer](#-观察者observer) | | [☔ 保护代理 Protection Proxy](#-保护代理模式protection-proxy) |
| [🐉 状态 State](#-状态state) | | [🍬 虚拟代理 Virtual Proxy](#-虚拟代理virtual-proxy) |
| [💡 策略 Strategy](#-策略strategy) | | |
| [📝 模板方法 Templdate Method](#-template-method) | | |
| [🏃 访问者 Visitor](#-访问者visitor) | | |
行为型模式
========
>在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
🐝 责任链(Chain Of Responsibility)
------------------------------
责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。
### 示例:
```swift
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
```
### 用法
```swift
// 创建一系列的钱堆,并将其链接起来:10<20<50<100
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// 创建 ATM 实例
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
```
👫 命令(Command)
------------
命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
* 重复多次
* 取消(如果该对象有实现的话)
* 取消后又再重做
### 示例:
```swift
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
```
### 用法
```swift
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
```
🎶 解释器(Interpreter)
------------------
给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
### 示例:
```swift
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
```
### 用法
```swift
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
```
🍫 迭代器(Iterator)
---------------
迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。
### 示例:
```swift
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
```
### 用法
```swift
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
```
💐 中介者(Mediator)
---------------
用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。
### 示例:
```swift
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
```
### 用法
```swift
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
```
💾 备忘录(Memento)
--------------
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
### 示例:
```swift
typealias Memento = [String: String]
```
发起人(Originator)
```swift
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
```
管理者(Caretaker)
```swift
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
```
### 用法
```swift
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
```
👓 观察者(Observer)
---------------
一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知
### 示例:
```swift
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
```
### 用法
```swift
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
```
🐉 状态(State)
---------
在状态模式中,对象的行为是基于它的内部状态而改变的。
这个模式允许某个类对象在运行时发生改变。
### 示例:
```swift
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
```
### 用法
```swift
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
```
💡 策略(Strategy)
--------------
对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:
* 定义了一族算法(业务规则);
* 封装了每个算法;
* 这族的算法可互换代替(interchangeable)。
### 示例:
```swift
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
```
### 用法
```swift
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
```
📝 模板方法模式
-----------
模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。
### 示例:
```swift
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
```
### 用法
```swift
let roseGarden = RoseGarden()
roseGarden.prepare()
```
🏃 访问者(Visitor)
--------------
封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
### 示例:
```swift
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
```
### 用法
```swift
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
```
创建型模式
========
> 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)
🌰 抽象工厂(Abstract Factory)
-------------
抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创建这一主题的具体对象。
### 示例:
协议
```swift
protocol BurgerDescribing {
var ingredients: [String] { get }
}
struct CheeseBurger: BurgerDescribing {
let ingredients: [String]
}
protocol BurgerMaking {
func make() -> BurgerDescribing
}
// 工厂方法实现
final class BigKahunaBurger: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
}
}
final class JackInTheBox: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
}
}
```
抽象工厂
```swift
enum BurgerFactoryType: BurgerMaking {
case bigKahuna
case jackInTheBox
func make() -> BurgerDescribing {
switch self {
case .bigKahuna:
return BigKahunaBurger().make()
case .jackInTheBox:
return JackInTheBox().make()
}
}
}
```
### 用法
```swift
let bigKahuna = BurgerFactoryType.bigKahuna.make()
let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
```
👷 生成器(Builder)
--------------
一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
### 示例:
```swift
final class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
```
### 用法
```swift
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
```
🏭 工厂方法(Factory Method)
-----------------------
定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
### 示例:
```swift
protocol CurrencyDescribing {
var symbol: String { get }
var code: String { get }
}
final class Euro: CurrencyDescribing {
var symbol: String {
return "€"
}
var code: String {
return "EUR"
}
}
final class UnitedStatesDolar: CurrencyDescribing {
var symbol: String {
return "$"
}
var code: String {
return "USD"
}
}
enum Country {
case unitedStates
case spain
case uk
case greece
}
enum CurrencyFactory {
static func currency(for country: Country) -> CurrencyDescribing? {
switch country {
case .spain, .greece:
return Euro()
case .unitedStates:
return UnitedStatesDolar()
default:
return nil
}
}
}
```
### 用法
```swift
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
```
🔂 单态(Monostate)
------------
单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。
因此,在这种情况下,单态会将状态保存为静态,而不是将整个实例保存为单例。
[单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
### 示例:
```swift
class Settings {
enum Theme {
case `default`
case old
case new
}
private static var theme: Theme?
var currentTheme: Theme {
get { Settings.theme ?? .default }
set(newTheme) { Settings.theme = newTheme }
}
}
```
### 用法:
```swift
import SwiftUI
// 改变主题
let settings = Settings() // 开始使用主题 .old
settings.currentTheme = .new // 改变主题为 .new
// 界面一
let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
// 界面二
let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
```
🃏 原型(Prototype)
--------------
通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
### 示例:
```swift
class MoonWorker {
let name: String
var health: Int = 100
init(name: String) {
self.name = name
}
func clone() -> MoonWorker {
return MoonWorker(name: name)
}
}
```
### 用法
```swift
let prototype = MoonWorker(name: "Sam Bell")
var bell1 = prototype.clone()
bell1.health = 12
var bell2 = prototype.clone()
bell2.health = 23
var bell3 = prototype.clone()
bell3.health = 0
```
💍 单例(Singleton)
--------------
单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为
### 示例:
```swift
final class ElonMusk {
static let shared = ElonMusk()
private init() {
// Private initialization to ensure just one instance is created.
}
}
```
### 用法
```swift
let elon = ElonMusk.shared // There is only one Elon Musk folks.
```
结构型模式(Structural)
====================
> 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)
🔌 适配器(Adapter)
--------------
适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
### 示例:
```swift
protocol NewDeathStarSuperLaserAiming {
var angleV: Double { get }
var angleH: Double { get }
}
```
**被适配者**
```swift
struct OldDeathStarSuperlaserTarget {
let angleHorizontal: Float
let angleVertical: Float
init(angleHorizontal: Float, angleVertical: Float) {
self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}
}
```
**适配器**
```swift
struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
private let target: OldDeathStarSuperlaserTarget
var angleV: Double {
return Double(target.angleVertical)
}
var angleH: Double {
return Double(target.angleHorizontal)
}
init(_ target: OldDeathStarSuperlaserTarget) {
self.target = target
}
}
```
### 用法
```swift
let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
let newFormat = NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV
```
🌉 桥接(Bridge)
-----------
桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
### 示例:
```swift
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
```
### 用法
```swift
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()
```
🌿 组合(Composite)
--------------
将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
### 示例:
组件(Component)
```swift
protocol Shape {
func draw(fillColor: String)
}
```
叶子节点(Leafs)
```swift
final class Square: Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle: Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
```
组合
```swift
final class Whiteboard: Shape {
private lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
```
### 用法
```swift
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")
```
🍧 修饰(Decorator)
--------------
修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。
就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。
### 示例:
```swift
protocol CostHaving {
var cost: Double { get }
}
protocol IngredientsHaving {
var ingredients: [String] { get }
}
typealias BeverageDataHaving = CostHaving & IngredientsHaving
struct SimpleCoffee: BeverageDataHaving {
let cost: Double = 1.0
let ingredients = ["Water", "Coffee"]
}
protocol BeverageHaving: BeverageDataHaving {
var beverage: BeverageDataHaving { get }
}
struct Milk: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Milk"]
}
}
struct WhipCoffee: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Whip"]
}
}
```
### 用法
```swift
var someCoffee: BeverageDataHaving = SimpleCoffee()
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = Milk(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = WhipCoffee(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
```
🎁 外观(Facade)
-----------
外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
### 示例:
```swift
final class Defaults {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
subscript(key: String) -> String? {
get {
return defaults.string(forKey: key)
}
set {
defaults.set(newValue, forKey: key)
}
}
}
```
### 用法
```swift
let storage = Defaults()
// Store
storage["Bishop"] = "Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]
```
🍃 享元(Flyweight)
--------------
使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。
### 示例:
```swift
// 特指咖啡生成的对象会是享元
struct SpecialityCoffee {
let origin: String
}
protocol CoffeeSearching {
func search(origin: String) -> SpecialityCoffee?
}
// 菜单充当特制咖啡享元对象的工厂和缓存
final class Menu: CoffeeSearching {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func search(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private let menu: CoffeeSearching
init(menu: CoffeeSearching) {
self.menu = menu
}
func takeOrder(origin: String, table: Int) {
orders[table] = menu.search(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
```
### 用法
```swift
let coffeeShop = CoffeeShop(menu: Menu())
coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
coffeeShop.serve()
```
☔ 保护代理模式(Protection Proxy)
------------------
在代理模式中,创建一个类代表另一个底层类的功能。
保护代理用于限制访问。
### 示例:
```swift
protocol DoorOpening {
func open(doors: String) -> String
}
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "pass" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
```
### 用法
```swift
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password: "pass")
computer.open(doors: podBay)
```
🍬 虚拟代理(Virtual Proxy)
----------------
在代理模式中,创建一个类代表另一个底层类的功能。
虚拟代理用于对象的需时加载。
### 示例:
```swift
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
```
### 用法
```swift
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()
```
Info
====
📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
================================================
FILE: README.md
================================================
Design Patterns implemented in Swift 5.0
========================================
A short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns.playground.zip)).
### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)
👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)
👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。
🚀 How to generate README, Playground and zip from source: [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)
```swift
print("Welcome!")
```
## Table of Contents
| [Behavioral](#behavioral) | [Creational](#creational) | [Structural](#structural) |
| ------------------------------------------------------ | ---------------------------------------- | ---------------------------------------- |
| [🐝 Chain Of Responsibility](#-chain-of-responsibility) | [🌰 Abstract Factory](#-abstract-factory) | [🔌 Adapter](#-adapter) |
| [👫 Command](#-command) | [👷 Builder](#-builder) | [🌉 Bridge](#-bridge) |
| [🎶 Interpreter](#-interpreter) | [🏭 Factory Method](#-factory-method) | [🌿 Composite](#-composite) |
| [🍫 Iterator](#-iterator) | [🔂 Monostate](#-monostate) | [🍧 Decorator](#-decorator) |
| [💐 Mediator](#-mediator) | [🃏 Prototype](#-prototype) | [🎁 Façade](#-fa-ade) |
| [💾 Memento](#-memento) | [💍 Singleton](#-singleton) | [🍃 Flyweight](#-flyweight) |
| [👓 Observer](#-observer) | | [☔ Protection Proxy](#-protection-proxy) |
| [🐉 State](#-state) | | [🍬 Virtual Proxy](#-virtual-proxy) |
| [💡 Strategy](#-strategy) | | |
| [📝 Template Method](#-template-method) | | |
| [🏃 Visitor](#-visitor) | | |
Behavioral
==========
>In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
🐝 Chain Of Responsibility
--------------------------
The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
### Example:
```swift
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
```
### Usage
```swift
// Create piles of money and link them together 10 < 20 < 50 < 100.**
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// Build ATM.
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
```
👫 Command
----------
The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
### Example:
```swift
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
```
### Usage:
```swift
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
```
🎶 Interpreter
--------------
The interpreter pattern is used to evaluate sentences in a language.
### Example
```swift
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
```
### Usage
```swift
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
```
🍫 Iterator
-----------
The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
### Example:
```swift
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
```
### Usage
```swift
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
```
💐 Mediator
-----------
The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
### Example
```swift
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
```
### Usage
```swift
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
```
💾 Memento
----------
The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
### Example
```swift
typealias Memento = [String: String]
```
Originator
```swift
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
```
Caretaker
```swift
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
```
### Usage
```swift
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
```
👓 Observer
-----------
The observer pattern is used to allow an object to publish changes to its state.
Other objects subscribe to be immediately notified of any changes.
### Example
```swift
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
```
### Usage
```swift
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
```
🐉 State
---------
The state pattern is used to alter the behaviour of an object as its internal state changes.
The pattern allows the class for an object to apparently change at run-time.
### Example
```swift
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
```
### Usage
```swift
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
```
💡 Strategy
-----------
The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
### Example
```swift
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
```
### Usage
```swift
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
```
📝 Template Method
-----------
The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.
### Example
```swift
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
```
### Usage
```swift
let roseGarden = RoseGarden()
roseGarden.prepare()
```
🏃 Visitor
----------
The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
### Example
```swift
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
```
### Usage
```swift
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
```
Creational
==========
> In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
🌰 Abstract Factory
-------------------
The abstract factory pattern is used to provide a client with a set of related or dependant objects.
The "family" of objects created by the factory are determined at run-time.
### Example
Protocols
```swift
protocol BurgerDescribing {
var ingredients: [String] { get }
}
struct CheeseBurger: BurgerDescribing {
let ingredients: [String]
}
protocol BurgerMaking {
func make() -> BurgerDescribing
}
// Number implementations with factory methods
final class BigKahunaBurger: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Lettuce", "Tomato"])
}
}
final class JackInTheBox: BurgerMaking {
func make() -> BurgerDescribing {
return CheeseBurger(ingredients: ["Cheese", "Burger", "Tomato", "Onions"])
}
}
```
Abstract factory
```swift
enum BurgerFactoryType: BurgerMaking {
case bigKahuna
case jackInTheBox
func make() -> BurgerDescribing {
switch self {
case .bigKahuna:
return BigKahunaBurger().make()
case .jackInTheBox:
return JackInTheBox().make()
}
}
}
```
### Usage
```swift
let bigKahuna = BurgerFactoryType.bigKahuna.make()
let jackInTheBox = BurgerFactoryType.jackInTheBox.make()
```
👷 Builder
----------
The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm.
An external class controls the construction algorithm.
### Example
```swift
final class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
```
### Usage
```swift
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
```
🏭 Factory Method
-----------------
The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
### Example
```swift
protocol CurrencyDescribing {
var symbol: String { get }
var code: String { get }
}
final class Euro: CurrencyDescribing {
var symbol: String {
return "€"
}
var code: String {
return "EUR"
}
}
final class UnitedStatesDolar: CurrencyDescribing {
var symbol: String {
return "$"
}
var code: String {
return "USD"
}
}
enum Country {
case unitedStates
case spain
case uk
case greece
}
enum CurrencyFactory {
static func currency(for country: Country) -> CurrencyDescribing? {
switch country {
case .spain, .greece:
return Euro()
case .unitedStates:
return UnitedStatesDolar()
default:
return nil
}
}
}
```
### Usage
```swift
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode
```
🔂 Monostate
------------
The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints.
So in that case, monostate saves the state as static instead of the entire instance as a singleton.
[SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)
### Example:
```swift
class Settings {
enum Theme {
case `default`
case old
case new
}
private static var theme: Theme?
var currentTheme: Theme {
get { Settings.theme ?? .default }
set(newTheme) { Settings.theme = newTheme }
}
}
```
### Usage:
```swift
import SwiftUI
// When change the theme
let settings = Settings() // Starts using theme .old
settings.currentTheme = .new // Change theme to .new
// On screen 1
let screenColor: Color = Settings().currentTheme == .old ? .gray : .white
// On screen 2
let screenTitle: String = Settings().currentTheme == .old ? "Itunes Connect" : "App Store Connect"
```
🃏 Prototype
------------
The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
This practise is particularly useful when the construction of a new object is inefficient.
### Example
```swift
class MoonWorker {
let name: String
var health: Int = 100
init(name: String) {
self.name = name
}
func clone() -> MoonWorker {
return MoonWorker(name: name)
}
}
```
### Usage
```swift
let prototype = MoonWorker(name: "Sam Bell")
var bell1 = prototype.clone()
bell1.health = 12
var bell2 = prototype.clone()
bell2.health = 23
var bell3 = prototype.clone()
bell3.health = 0
```
💍 Singleton
------------
The singleton pattern ensures that only one object of a particular class is ever created.
All further references to objects of the singleton class refer to the same underlying instance.
There are very few applications, do not overuse this pattern!
### Example:
```swift
final class ElonMusk {
static let shared = ElonMusk()
private init() {
// Private initialization to ensure just one instance is created.
}
}
```
### Usage:
```swift
let elon = ElonMusk.shared // There is only one Elon Musk folks.
```
Structural
==========
>In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)
🔌 Adapter
----------
The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
### Example
```swift
protocol NewDeathStarSuperLaserAiming {
var angleV: Double { get }
var angleH: Double { get }
}
```
**Adaptee**
```swift
struct OldDeathStarSuperlaserTarget {
let angleHorizontal: Float
let angleVertical: Float
init(angleHorizontal: Float, angleVertical: Float) {
self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}
}
```
**Adapter**
```swift
struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
private let target: OldDeathStarSuperlaserTarget
var angleV: Double {
return Double(target.angleVertical)
}
var angleH: Double {
return Double(target.angleHorizontal)
}
init(_ target: OldDeathStarSuperlaserTarget) {
self.target = target
}
}
```
### Usage
```swift
let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
let newFormat = NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV
```
🌉 Bridge
----------
The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
### Example
```swift
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
```
### Usage
```swift
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()
```
🌿 Composite
-------------
The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
### Example
Component
```swift
protocol Shape {
func draw(fillColor: String)
}
```
Leafs
```swift
final class Square: Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle: Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
```
Composite
```swift
final class Whiteboard: Shape {
private lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
```
### Usage:
```swift
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")
```
🍧 Decorator
------------
The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class.
This provides a flexible alternative to using inheritance to modify behaviour.
### Example
```swift
protocol CostHaving {
var cost: Double { get }
}
protocol IngredientsHaving {
var ingredients: [String] { get }
}
typealias BeverageDataHaving = CostHaving & IngredientsHaving
struct SimpleCoffee: BeverageDataHaving {
let cost: Double = 1.0
let ingredients = ["Water", "Coffee"]
}
protocol BeverageHaving: BeverageDataHaving {
var beverage: BeverageDataHaving { get }
}
struct Milk: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Milk"]
}
}
struct WhipCoffee: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Whip"]
}
}
```
### Usage:
```swift
var someCoffee: BeverageDataHaving = SimpleCoffee()
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = Milk(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = WhipCoffee(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
```
🎁 Façade
---------
The facade pattern is used to define a simplified interface to a more complex subsystem.
### Example
```swift
final class Defaults {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
subscript(key: String) -> String? {
get {
return defaults.string(forKey: key)
}
set {
defaults.set(newValue, forKey: key)
}
}
}
```
### Usage
```swift
let storage = Defaults()
// Store
storage["Bishop"] = "Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]
```
## 🍃 Flyweight
The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.
### Example
```swift
// Instances of SpecialityCoffee will be the Flyweights
struct SpecialityCoffee {
let origin: String
}
protocol CoffeeSearching {
func search(origin: String) -> SpecialityCoffee?
}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
final class Menu: CoffeeSearching {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func search(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private let menu: CoffeeSearching
init(menu: CoffeeSearching) {
self.menu = menu
}
func takeOrder(origin: String, table: Int) {
orders[table] = menu.search(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
```
### Usage
```swift
let coffeeShop = CoffeeShop(menu: Menu())
coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
coffeeShop.serve()
```
☔ Protection Proxy
------------------
The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
Protection proxy is restricting access.
### Example
```swift
protocol DoorOpening {
func open(doors: String) -> String
}
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "pass" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
```
### Usage
```swift
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password: "pass")
computer.open(doors: podBay)
```
🍬 Virtual Proxy
----------------
The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.
Virtual proxy is used for loading object on demand.
### Example
```swift
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
```
### Usage
```swift
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()
```
Info
====
📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)
================================================
FILE: generate-playground-cn.sh
================================================
#!/bin/bash
# Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash.
# Would love to rewrite it in Swift soon.
combineSwiftCN() {
cat source-cn/startComment > $2
cat $1/header.md >> $2
cat source-cn/contents.md >> $2
cat source-cn/endComment >> $2
cat source-cn/imports.swift >> $2
cat $1/*.swift >> $2
{ rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
}
move() {
mv $1.swift Design-Patterns-CN.playground/Pages/$1.xcplaygroundpage/Contents.swift
}
playground() {
combineSwiftCN source-cn/$1 $1.swift
move $1
}
combineMarkdown() {
cat $1/header.md > $2
{ rm $2 && awk '{gsub("\\*/", "", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("/\\*:", "", $0); print}' > $2; } < $2
cat source-cn/startSwiftCode >> $2
cat $1/*.swift >> $2
{ rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("\\*/", "\n```swift", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("/\\*:", "```\n", $0); print}' > $2; } < $2
cat source-cn/endSwiftCode >> $2
{ rm $2 && awk '{gsub("```swift```", "", $0); print}' > $2; } < $2
cat $2 >> README-CN.md
rm $2
}
readme() {
combineMarkdown source-cn/$1 $1.md
}
playground Index
playground Behavioral
playground Creational
playground Structural
zip -r -X Design-Patterns-CN.playground.zip ./Design-Patterns-CN.playground
echo "" > README-CN.md
readme Index
cat source-cn/contentsReadme.md >> README-CN.md
readme Behavioral
readme Creational
readme Structural
cat source-cn/footer.md >> README-CN.md
================================================
FILE: generate-playground.sh
================================================
#!/bin/bash
# Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash.
# Would love to rewrite it in Swift soon.
combineSwift() {
cat source/startComment > $2
cat $1/header.md >> $2
cat source/contents.md >> $2
cat source/endComment >> $2
cat source/imports.swift >> $2
cat $1/*.swift >> $2
{ rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
}
move() {
mv $1.swift Design-Patterns.playground/Pages/$1.xcplaygroundpage/Contents.swift
}
playground() {
combineSwift source/$1 $1.swift
move $1
}
combineMarkdown() {
cat $1/header.md > $2
{ rm $2 && awk '{gsub("\\*/", "", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("/\\*:", "", $0); print}' > $2; } < $2
cat source/startSwiftCode >> $2
cat $1/*.swift >> $2
{ rm $2 && awk '{gsub("\\*//\\*:", "", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("\\*/", "\n```swift", $0); print}' > $2; } < $2
{ rm $2 && awk '{gsub("/\\*:", "```\n", $0); print}' > $2; } < $2
cat source/endSwiftCode >> $2
{ rm $2 && awk '{gsub("```swift```", "", $0); print}' > $2; } < $2
cat $2 >> README.md
rm $2
}
readme() {
combineMarkdown source/$1 $1.md
}
playground Index
playground Behavioral
playground Creational
playground Structural
zip -r -X Design-Patterns.playground.zip ./Design-Patterns.playground
echo "" > README.md
readme Index
cat source/contentsReadme.md >> README.md
readme Behavioral
readme Creational
readme Structural
cat source/footer.md >> README.md
================================================
FILE: source/Index/header.md
================================================
Design Patterns implemented in Swift 5.0
========================================
A short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns.playground.zip)).
### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)
👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)
👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。
🚀 How to generate README, Playground and zip from source: [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)
================================================
FILE: source/Index/welcome.swift
================================================
print("Welcome!")
================================================
FILE: source/behavioral/chain_of_responsibility.swift
================================================
/*:
🐝 Chain Of Responsibility
--------------------------
The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
### Example:
*/
protocol Withdrawing {
func withdraw(amount: Int) -> Bool
}
final class MoneyPile: Withdrawing {
let value: Int
var quantity: Int
var next: Withdrawing?
init(value: Int, quantity: Int, next: Withdrawing?) {
self.value = value
self.quantity = quantity
self.next = next
}
func withdraw(amount: Int) -> Bool {
var amount = amount
func canTakeSomeBill(want: Int) -> Bool {
return (want / self.value) > 0
}
var quantity = self.quantity
while canTakeSomeBill(want: amount) {
if quantity == 0 {
break
}
amount -= self.value
quantity -= 1
}
guard amount > 0 else {
return true
}
if let next {
return next.withdraw(amount: amount)
}
return false
}
}
final class ATM: Withdrawing {
private var hundred: Withdrawing
private var fifty: Withdrawing
private var twenty: Withdrawing
private var ten: Withdrawing
private var startPile: Withdrawing {
return self.hundred
}
init(hundred: Withdrawing,
fifty: Withdrawing,
twenty: Withdrawing,
ten: Withdrawing) {
self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}
func withdraw(amount: Int) -> Bool {
return startPile.withdraw(amount: amount)
}
}
/*:
### Usage
*/
// Create piles of money and link them together 10 < 20 < 50 < 100.**
let ten = MoneyPile(value: 10, quantity: 6, next: nil)
let twenty = MoneyPile(value: 20, quantity: 2, next: ten)
let fifty = MoneyPile(value: 50, quantity: 2, next: twenty)
let hundred = MoneyPile(value: 100, quantity: 1, next: fifty)
// Build ATM.
var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount: 310) // Cannot because ATM has only 300
atm.withdraw(amount: 100) // Can withdraw - 1x100
================================================
FILE: source/behavioral/command.swift
================================================
/*:
👫 Command
----------
The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
### Example:
*/
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### Usage:
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
================================================
FILE: source/behavioral/header.md
================================================
Behavioral
==========
>In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)
================================================
FILE: source/behavioral/interpreter.swift
================================================
/*:
🎶 Interpreter
--------------
The interpreter pattern is used to evaluate sentences in a language.
### Example
*/
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
/*:
### Usage
*/
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
================================================
FILE: source/behavioral/iterator.swift
================================================
/*:
🍫 Iterator
-----------
The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
### Example:
*/
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
/*:
### Usage
*/
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}
================================================
FILE: source/behavioral/mediator.swift
================================================
/*:
💐 Mediator
-----------
The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
### Example
*/
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
/*:
### Usage
*/
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
================================================
FILE: source/behavioral/memento.swift
================================================
/*:
💾 Memento
----------
The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
### Example
*/
typealias Memento = [String: String]
/*:
Originator
*/
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
/*:
Caretaker
*/
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
/*:
### Usage
*/
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
================================================
FILE: source/behavioral/observer.swift
================================================
/*:
👓 Observer
-----------
The observer pattern is used to allow an object to publish changes to its state.
Other objects subscribe to be immediately notified of any changes.
### Example
*/
protocol PropertyObserver : class {
func willChange(propertyName: String, newPropertyValue: Any?)
func didChange(propertyName: String, oldPropertyValue: Any?)
}
final class TestChambers {
weak var observer:PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
final class Observer : PropertyObserver {
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
/*:
### Usage
*/
var observerInstance = Observer()
var testChambers = TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
================================================
FILE: source/behavioral/state.swift
================================================
/*:
🐉 State
---------
The state pattern is used to alter the behaviour of an object as its internal state changes.
The pattern allows the class for an object to apparently change at run-time.
### Example
*/
final class Context {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get { return state.isAuthorized(context: self) }
}
var userId: String? {
get { return state.userId(context: self) }
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool { return false }
func userId(context: Context) -> String? { return nil }
}
class AuthorizedState: State {
let userId: String
init(userId: String) { self.userId = userId }
func isAuthorized(context: Context) -> Bool { return true }
func userId(context: Context) -> String? { return userId }
}
/*:
### Usage
*/
let userContext = Context()
(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId: "admin")
(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()
(userContext.isAuthorized, userContext.userId)
================================================
FILE: source/behavioral/strategy.swift
================================================
/*:
💡 Strategy
-----------
The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
### Example
*/
struct TestSubject {
let pupilDiameter: Double
let blushResponse: Double
let isOrganic: Bool
}
protocol RealnessTesting: AnyObject {
func testRealness(_ testSubject: TestSubject) -> Bool
}
final class VoightKampffTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0
}
}
final class GeneticTest: RealnessTesting {
func testRealness(_ testSubject: TestSubject) -> Bool {
return testSubject.isOrganic
}
}
final class BladeRunner {
private let strategy: RealnessTesting
init(test: RealnessTesting) {
self.strategy = test
}
func testIfAndroid(_ testSubject: TestSubject) -> Bool {
return !strategy.testRealness(testSubject)
}
}
/*:
### Usage
*/
let rachel = TestSubject(pupilDiameter: 30.2,
blushResponse: 0.3,
isOrganic: false)
// Deckard is using a traditional test
let deckard = BladeRunner(test: VoightKampffTest())
let isRachelAndroid = deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
let gaff = BladeRunner(test: GeneticTest())
let isDeckardAndroid = gaff.testIfAndroid(rachel)
================================================
FILE: source/behavioral/template_method.swift
================================================
/*:
📝 Template Method
-----------
The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.
### Example
*/
protocol Garden {
func prepareSoil()
func plantSeeds()
func waterPlants()
func prepareGarden()
}
extension Garden {
func prepareGarden() {
prepareSoil()
plantSeeds()
waterPlants()
}
}
final class RoseGarden: Garden {
func prepare() {
prepareGarden()
}
func prepareSoil() {
print ("prepare soil for rose garden")
}
func plantSeeds() {
print ("plant seeds for rose garden")
}
func waterPlants() {
print ("water the rose garden")
}
}
/*:
### Usage
*/
let roseGarden = RoseGarden()
roseGarden.prepare()
================================================
FILE: source/behavioral/visitor.swift
================================================
/*:
🏃 Visitor
----------
The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
### Example
*/
protocol PlanetVisitor {
func visit(planet: PlanetAlderaan)
func visit(planet: PlanetCoruscant)
func visit(planet: PlanetTatooine)
func visit(planet: MoonJedha)
}
protocol Planet {
func accept(visitor: PlanetVisitor)
}
final class MoonJedha: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetAlderaan: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetCoruscant: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class PlanetTatooine: Planet {
func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }
}
final class NameVisitor: PlanetVisitor {
var name = ""
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
func visit(planet: PlanetTatooine) { name = "Tatooine" }
func visit(planet: MoonJedha) { name = "Jedha" }
}
/*:
### Usage
*/
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]
let names = planets.map { (planet: Planet) -> String in
let visitor = NameVisitor()
planet.accept(visitor: visitor)
return visitor.name
}
names
================================================
FILE: source/contents.md
================================================
## Table of Contents
* [Behavioral](Behavioral)
* [Creational](Creational)
* [Structural](Structural)
================================================
FILE: source/contentsReadme.md
================================================
## Table of Contents
| [Behavioral](#behavioral) | [Creational](#creational) | [Structural](#structural) |
| ------------------------------------------------------ | ---------------------------------------- | ---------------------------------------- |
| [🐝 Chain Of Responsibility](#-chain-of-responsibility) | [🌰 Abstract Factory](#-abstract-factory) | [🔌 Adapter](#-adapter) |
| [👫 Command](#-command) | [👷 Builder](#-builder) | [🌉 Bridge](#-bridge)
gitextract_rec1cm42/
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── generate-playground.yml
├── .gitignore
├── CONTRIBUTING-CN.md
├── CONTRIBUTING.md
├── Design-Patterns-CN.playground/
│ ├── Pages/
│ │ ├── Behavioral.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Creational.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Index.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ └── Structural.xcplaygroundpage/
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
│ └── contents.xcplayground
├── Design-Patterns.playground/
│ ├── Pages/
│ │ ├── Behavioral.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Creational.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ ├── Index.xcplaygroundpage/
│ │ │ └── Contents.swift
│ │ └── Structural.xcplaygroundpage/
│ │ ├── Contents.swift
│ │ └── timeline.xctimeline
│ └── contents.xcplayground
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README-CN.md
├── README.md
├── generate-playground-cn.sh
├── generate-playground.sh
├── source/
│ ├── Index/
│ │ ├── header.md
│ │ └── welcome.swift
│ ├── behavioral/
│ │ ├── chain_of_responsibility.swift
│ │ ├── command.swift
│ │ ├── header.md
│ │ ├── interpreter.swift
│ │ ├── iterator.swift
│ │ ├── mediator.swift
│ │ ├── memento.swift
│ │ ├── observer.swift
│ │ ├── state.swift
│ │ ├── strategy.swift
│ │ ├── template_method.swift
│ │ └── visitor.swift
│ ├── contents.md
│ ├── contentsReadme.md
│ ├── creational/
│ │ ├── abstract_factory.swift
│ │ ├── builder.swift
│ │ ├── factory.swift
│ │ ├── header.md
│ │ ├── monostate.swift
│ │ ├── prototype.swift
│ │ └── singleton.swift
│ ├── endComment
│ ├── endSwiftCode
│ ├── footer.md
│ ├── imports.swift
│ ├── startComment
│ ├── startSwiftCode
│ └── structural/
│ ├── adapter.swift
│ ├── bridge.swift
│ ├── composite.swift
│ ├── decorator.swift
│ ├── facade.swift
│ ├── flyweight.swift
│ ├── header.md
│ ├── protection_proxy.swift
│ └── virtual_proxy.swift
└── source-cn/
├── Index/
│ ├── header.md
│ └── welcome.swift
├── behavioral/
│ ├── chain_of_responsibility.swift
│ ├── command.swift
│ ├── header.md
│ ├── interpreter.swift
│ ├── iterator.swift
│ ├── mediator.swift
│ ├── memento.swift
│ ├── observer.swift
│ ├── state.swift
│ ├── strategy.swift
│ ├── template_method.swift
│ └── visitor.swift
├── contents.md
├── contentsReadme.md
├── creational/
│ ├── abstract_factory.swift
│ ├── builder.swift
│ ├── factory.swift
│ ├── header.md
│ ├── monostate.swift
│ ├── prototype.swift
│ └── singleton.swift
├── endComment
├── endSwiftCode
├── footer.md
├── imports.swift
├── startComment
├── startSwiftCode
└── structural/
├── adapter.swift
├── bridge.swift
├── composite.swift
├── decorator.swift
├── facade.swift
├── flyweight.swift
├── header.md
├── protection_proxy.swift
└── virtual_proxy.swift
Condensed preview — 99 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (261K chars).
[
{
"path": ".github/FUNDING.yml",
"chars": 64,
"preview": "# These are supported funding model platforms\n\ngithub: ochococo\n"
},
{
"path": ".github/workflows/generate-playground.yml",
"chars": 2484,
"preview": "name: Generate Playground Files and READMES\n\n# Controls when the action will run. Triggers the workflow on push or pull "
},
{
"path": ".gitignore",
"chars": 74,
"preview": ".DS_Store\nUserInterfaceState.xcuserstate\nplayground.xcworkspace\nxcuserdata"
},
{
"path": "CONTRIBUTING-CN.md",
"chars": 514,
"preview": "如何贡献(中文版)?\n==================\n\n- 你很棒!\n- 仅建议编辑`source-cn`目录中的文件,其余内容是自动生成的并已翻译\n- 提交更改\n- 本地运行`generate-playground-cn.s"
},
{
"path": "CONTRIBUTING.md",
"chars": 423,
"preview": "How to contribute?\n==================\n\n- You are awesome!\n- Only editing files inside `source` is recommended, the rest "
},
{
"path": "Design-Patterns-CN.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift",
"chars": 16275,
"preview": "/*:\n\n 行为型模式\n ========\n \n >在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。\n >\n >**来源:** [维基百科](https://z"
},
{
"path": "Design-Patterns-CN.playground/Pages/Creational.xcplaygroundpage/Contents.swift",
"chars": 5335,
"preview": "/*:\n\n 创建型模式\n ========\n \n > 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题"
},
{
"path": "Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift",
"chars": 433,
"preview": "/*:\n\n设计模式(Swift 5.0 实现)\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/o"
},
{
"path": "Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/Contents.swift",
"chars": 7747,
"preview": "/*:\n\n结构型模式(Structural)\n====================\n\n> 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。\n>\n>**来源:** [维基百科](https://zh.w"
},
{
"path": "Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline",
"chars": 120,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Timeline\n version = \"3.0\">\n <TimelineItems>\n </TimelineItems>\n</Timeline>\n"
},
{
"path": "Design-Patterns-CN.playground/contents.xcplayground",
"chars": 298,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='6.0' target-platform='ios' display-mode='re"
},
{
"path": "Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift",
"chars": 17687,
"preview": "/*:\n\nBehavioral\n==========\n\n>In software engineering, behavioral design patterns are design patterns that identify commo"
},
{
"path": "Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift",
"chars": 6683,
"preview": "/*:\n\nCreational\n==========\n\n> In software engineering, creational design patterns are design patterns that deal with obj"
},
{
"path": "Design-Patterns.playground/Pages/Index.xcplaygroundpage/Contents.swift",
"chars": 809,
"preview": "/*:\n\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA short cheat-sheet with Xcode 1"
},
{
"path": "Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift",
"chars": 8838,
"preview": "/*:\n\nStructural\n==========\n\n>In software engineering, structural design patterns are design patterns that ease the desig"
},
{
"path": "Design-Patterns.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline",
"chars": 120,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Timeline\n version = \"3.0\">\n <TimelineItems>\n </TimelineItems>\n</Timeline>\n"
},
{
"path": "Design-Patterns.playground/contents.xcplayground",
"chars": 298,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='6.0' target-platform='ios' display-mode='re"
},
{
"path": "LICENSE",
"chars": 35120,
"preview": "GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation,"
},
{
"path": "PULL_REQUEST_TEMPLATE.md",
"chars": 438,
"preview": "- [ ] Read [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md])\n- [ ] On"
},
{
"path": "README-CN.md",
"chars": 32538,
"preview": "\n\n设计模式(Swift 5.0 实现)\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ocho"
},
{
"path": "README.md",
"chars": 36009,
"preview": "\n\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA short cheat-sheet with Xcode 10.2"
},
{
"path": "generate-playground-cn.sh",
"chars": 1548,
"preview": "#!/bin/bash\n\n# Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash. \n# Would "
},
{
"path": "generate-playground.sh",
"chars": 1493,
"preview": "#!/bin/bash\n\n# Note: I think this part is absolute garbage but it's a snapshot of my current skills with Bash. \n# Would "
},
{
"path": "source/Index/header.md",
"chars": 668,
"preview": "\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA short cheat-sheet with Xcode 10.2 "
},
{
"path": "source/Index/welcome.swift",
"chars": 19,
"preview": "\nprint(\"Welcome!\")\n"
},
{
"path": "source/behavioral/chain_of_responsibility.swift",
"chars": 2216,
"preview": "/*:\n🐝 Chain Of Responsibility\n--------------------------\n\nThe chain of responsibility pattern is used to process varied "
},
{
"path": "source/behavioral/command.swift",
"chars": 1270,
"preview": "/*:\n👫 Command\n----------\n\nThe command pattern is used to express a request, including the call to be made and all of its"
},
{
"path": "source/behavioral/header.md",
"chars": 350,
"preview": "\nBehavioral\n==========\n\n>In software engineering, behavioral design patterns are design patterns that identify common co"
},
{
"path": "source/behavioral/interpreter.swift",
"chars": 2543,
"preview": "/*:\n🎶 Interpreter\n--------------\n\nThe interpreter pattern is used to evaluate sentences in a language.\n\n### Example\n*/\n\n"
},
{
"path": "source/behavioral/iterator.swift",
"chars": 932,
"preview": "/*:\n🍫 Iterator\n-----------\n\nThe iterator pattern is used to provide a standard interface for traversing a collection of "
},
{
"path": "source/behavioral/mediator.swift",
"chars": 1522,
"preview": "/*:\n💐 Mediator\n-----------\n\nThe mediator pattern is used to reduce coupling between classes that communicate with each o"
},
{
"path": "source/behavioral/memento.swift",
"chars": 2042,
"preview": "/*:\n💾 Memento\n----------\n\nThe memento pattern is used to capture the current state of an object and store it in such a m"
},
{
"path": "source/behavioral/observer.swift",
"chars": 1442,
"preview": "/*:\n👓 Observer\n-----------\n\nThe observer pattern is used to allow an object to publish changes to its state.\nOther objec"
},
{
"path": "source/behavioral/state.swift",
"chars": 1417,
"preview": "/*:\n🐉 State\n---------\n\nThe state pattern is used to alter the behaviour of an object as its internal state changes.\nThe "
},
{
"path": "source/behavioral/strategy.swift",
"chars": 1428,
"preview": "/*:\n💡 Strategy\n-----------\n\nThe strategy pattern is used to create an interchangeable family of algorithms from which th"
},
{
"path": "source/behavioral/template_method.swift",
"chars": 945,
"preview": "/*:\n📝 Template Method\n-----------\n\n The template method pattern defines the steps of an algorithm and allows the redefin"
},
{
"path": "source/behavioral/visitor.swift",
"chars": 1438,
"preview": "/*:\n🏃 Visitor\n----------\n\nThe visitor pattern is used to separate a relatively complex set of structured data classes fr"
},
{
"path": "source/contents.md",
"chars": 104,
"preview": "\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n"
},
{
"path": "source/contentsReadme.md",
"chars": 1908,
"preview": "\n## Table of Contents\n\n| [Behavioral](#behavioral) | [Creational](#creational) "
},
{
"path": "source/creational/abstract_factory.swift",
"chars": 1296,
"preview": "/*:\n🌰 Abstract Factory\n-------------------\n\nThe abstract factory pattern is used to provide a client with a set of relat"
},
{
"path": "source/creational/builder.swift",
"chars": 1061,
"preview": "/*:\n👷 Builder\n----------\n\nThe builder pattern is used to create complex objects with constituent parts that must be crea"
},
{
"path": "source/creational/factory.swift",
"chars": 1374,
"preview": "/*:\n🏭 Factory Method\n-----------------\n\nThe factory pattern is used to replace class constructors, abstracting the proce"
},
{
"path": "source/creational/header.md",
"chars": 477,
"preview": "\nCreational\n==========\n\n> In software engineering, creational design patterns are design patterns that deal with object "
},
{
"path": "source/creational/monostate.swift",
"chars": 1109,
"preview": "/*:\n 🔂 Monostate\n ------------\n\n The monostate pattern is another way to achieve singularity. It works through a complet"
},
{
"path": "source/creational/prototype.swift",
"chars": 695,
"preview": "/*:\n🃏 Prototype\n------------\n\nThe prototype pattern is used to instantiate a new object by copying all of the properties"
},
{
"path": "source/creational/singleton.swift",
"chars": 541,
"preview": "/*:\n💍 Singleton\n------------\n\nThe singleton pattern ensures that only one object of a particular class is ever created.\n"
},
{
"path": "source/endComment",
"chars": 3,
"preview": "\n*/"
},
{
"path": "source/endSwiftCode",
"chars": 5,
"preview": "```\n\n"
},
{
"path": "source/footer.md",
"chars": 124,
"preview": "\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.as"
},
{
"path": "source/imports.swift",
"chars": 19,
"preview": "\nimport Foundation\n"
},
{
"path": "source/startComment",
"chars": 4,
"preview": "/*:\n"
},
{
"path": "source/startSwiftCode",
"chars": 10,
"preview": "\n\n```swift"
},
{
"path": "source/structural/adapter.swift",
"chars": 1172,
"preview": "/*:\n🔌 Adapter\n----------\n\nThe adapter pattern is used to provide a link between two otherwise incompatible types by wrap"
},
{
"path": "source/structural/bridge.swift",
"chars": 969,
"preview": "/*:\n🌉 Bridge\n----------\n\nThe bridge pattern is used to separate the abstract elements of a class from the implementation"
},
{
"path": "source/structural/composite.swift",
"chars": 959,
"preview": "/*:\n🌿 Composite\n-------------\n\nThe composite pattern is used to create hierarchical, recursive tree structures of relate"
},
{
"path": "source/structural/decorator.swift",
"chars": 1491,
"preview": "/*:\n🍧 Decorator\n------------\n\nThe decorator pattern is used to extend or alter the functionality of objects at run- time"
},
{
"path": "source/structural/facade.swift",
"chars": 611,
"preview": "/*:\n🎁 Façade\n---------\n\nThe facade pattern is used to define a simplified interface to a more complex subsystem.\n\n### Ex"
},
{
"path": "source/structural/flyweight.swift",
"chars": 1423,
"preview": "/*:\n## 🍃 Flyweight\nThe flyweight pattern is used to minimize memory usage or computational expenses by sharing as much a"
},
{
"path": "source/structural/header.md",
"chars": 269,
"preview": "\nStructural\n==========\n\n>In software engineering, structural design patterns are design patterns that ease the design by"
},
{
"path": "source/structural/protection_proxy.swift",
"chars": 1084,
"preview": "/*:\n☔ Protection Proxy\n------------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which"
},
{
"path": "source/structural/virtual_proxy.swift",
"chars": 730,
"preview": "/*:\n🍬 Virtual Proxy\n----------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which refe"
},
{
"path": "source-cn/Index/header.md",
"chars": 573,
"preview": "\n设计模式(Swift 5.0 实现)\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochoc"
},
{
"path": "source-cn/Index/welcome.swift",
"chars": 14,
"preview": "\nprint(\"您好!\")\n"
},
{
"path": "source-cn/behavioral/chain_of_responsibility.swift",
"chars": 2151,
"preview": "/*:\n🐝 责任链(Chain Of Responsibility)\n------------------------------\n\n责任链模式在面向对象程式设计里是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决"
},
{
"path": "source-cn/behavioral/command.swift",
"chars": 1164,
"preview": "/*:\n👫 命令(Command)\n ------------\n 命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:\n * 重复多次\n * 取消(如果该对象有实现的"
},
{
"path": "source-cn/behavioral/header.md",
"chars": 184,
"preview": "\n 行为型模式\n ========\n \n >在软件工程中, 行为型模式为设计模式的一种类型,用来识别对象之间的常用交流模式并加以实现。如此,可在进行这些交流活动时增强弹性。\n >\n >**来源:** [维基百科](https://zh.wi"
},
{
"path": "source-cn/behavioral/interpreter.swift",
"chars": 2526,
"preview": "/*:\n🎶 解释器(Interpreter)\n ------------------\n\n 给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。\n\n ### 示例:\n*/\n\nprotocol Integ"
},
{
"path": "source-cn/behavioral/iterator.swift",
"chars": 799,
"preview": "/*:\n🍫 迭代器(Iterator)\n ---------------\n\n 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。\n \n ### 示例:\n*/\nstruct Novella {\n let na"
},
{
"path": "source-cn/behavioral/mediator.swift",
"chars": 1346,
"preview": "/*:\n💐 中介者(Mediator)\n ---------------\n\n 用一个中介者对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使耦合松散,而且可以独立地改变它们之间的交互。\n\n ### 示例:\n*/\nproto"
},
{
"path": "source-cn/behavioral/memento.swift",
"chars": 1927,
"preview": "/*:\n💾 备忘录(Memento)\n--------------\n\n在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态\n\n### 示例:\n*/\ntypealias Memen"
},
{
"path": "source-cn/behavioral/observer.swift",
"chars": 1336,
"preview": "/*:\n👓 观察者(Observer)\n---------------\n\n一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知\n\n### 示例:\n*/\nprotocol PropertyObserver : cla"
},
{
"path": "source-cn/behavioral/state.swift",
"chars": 1292,
"preview": "/*:\n🐉 状态(State)\n---------\n\n在状态模式中,对象的行为是基于它的内部状态而改变的。\n这个模式允许某个类对象在运行时发生改变。\n\n### 示例:\n*/\nfinal class Context {\n\tprivate va"
},
{
"path": "source-cn/behavioral/strategy.swift",
"chars": 1389,
"preview": "/*:\n💡 策略(Strategy)\n--------------\n\n对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。策略模式:\n* 定义了一族算法(业务规则);\n* 封装了每个算法;\n* 这族的算法可互换代替(intercha"
},
{
"path": "source-cn/behavioral/template_method.swift",
"chars": 725,
"preview": "/*:\n📝 模板方法模式\n-----------\n\n 模板方法模式是一种行为设计模式, 它通过父类/协议中定义了一个算法的框架, 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。\n\n### 示例:\n*/\nprotocol Ga"
},
{
"path": "source-cn/behavioral/visitor.swift",
"chars": 1325,
"preview": "/*:\n🏃 访问者(Visitor)\n--------------\n\n封装某些作用于某种数据结构中各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。\n\n### 示例:\n*/\nprotocol PlanetVisito"
},
{
"path": "source-cn/contents.md",
"chars": 73,
"preview": "\n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)"
},
{
"path": "source-cn/contentsReadme.md",
"chars": 2294,
"preview": "\n## 目录\n\n| [行为型模式](#行为型模式) | [创建型模式](#创建型模式) | [结构型模式]"
},
{
"path": "source-cn/creational/abstract_factory.swift",
"chars": 1144,
"preview": "/*:\n🌰 抽象工厂(Abstract Factory)\n-------------\n\n抽象工厂模式提供了一种方式,可以将一组具有同一主题的单独的工厂封装起来。在正常使用中,客户端程序需要创建抽象工厂的具体实现,然后使用抽象工厂作为接口来创"
},
{
"path": "source-cn/creational/builder.swift",
"chars": 925,
"preview": "/*:\n👷 生成器(Builder)\n--------------\n\n一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。\n\n### 示例:\n*/\nfinal cl"
},
{
"path": "source-cn/creational/factory.swift",
"chars": 1252,
"preview": "/*:\n🏭 工厂方法(Factory Method)\n-----------------------\n\n定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。\n\n### 示例:\n*/\nprot"
},
{
"path": "source-cn/creational/header.md",
"chars": 216,
"preview": "\n 创建型模式\n ========\n \n > 创建型模式是处理对象创建的设计模式,试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题,或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。\n >"
},
{
"path": "source-cn/creational/monostate.swift",
"chars": 835,
"preview": "/*:\n 🔂 单态(Monostate)\n ------------\n\n 单态模式是实现单一共享的另一种方法。不同于单例模式,它通过完全不同的机制,在不限制构造方法的情况下实现单一共享特性。\n 因此,在这种情况下,单态会将状态保存为静态"
},
{
"path": "source-cn/creational/prototype.swift",
"chars": 517,
"preview": "/*:\n🃏 原型(Prototype)\n--------------\n\n通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。\n\n### 示例:\n*/\nclass MoonWo"
},
{
"path": "source-cn/creational/singleton.swift",
"chars": 347,
"preview": "/*:\n💍 单例(Singleton)\n--------------\n\n单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为\n\n### 示例:\n*/\nfinal class Elo"
},
{
"path": "source-cn/endComment",
"chars": 3,
"preview": "\n*/"
},
{
"path": "source-cn/endSwiftCode",
"chars": 5,
"preview": "```\n\n"
},
{
"path": "source-cn/footer.md",
"chars": 124,
"preview": "\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.as"
},
{
"path": "source-cn/imports.swift",
"chars": 19,
"preview": "\nimport Foundation\n"
},
{
"path": "source-cn/startComment",
"chars": 4,
"preview": "/*:\n"
},
{
"path": "source-cn/startSwiftCode",
"chars": 10,
"preview": "\n\n```swift"
},
{
"path": "source-cn/structural/adapter.swift",
"chars": 1085,
"preview": "/*:\n🔌 适配器(Adapter)\n--------------\n\n适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹"
},
{
"path": "source-cn/structural/bridge.swift",
"chars": 799,
"preview": "/*:\n🌉 桥接(Bridge)\n-----------\n\n桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。\n\n### 示例:\n*/\nprotocol Switch {\n var appliance: Appliance {"
},
{
"path": "source-cn/structural/composite.swift",
"chars": 828,
"preview": "/*:\n🌿 组合(Composite)\n--------------\n\n将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。\n\n### 示例:\n\n组件(Component)\n*/\npro"
},
{
"path": "source-cn/structural/decorator.swift",
"chars": 1349,
"preview": "/*:\n🍧 修饰(Decorator)\n--------------\n\n修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。\n就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。\n\n"
},
{
"path": "source-cn/structural/facade.swift",
"chars": 559,
"preview": "/*:\n🎁 外观(Facade)\n-----------\n\n外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。\n\n### 示例:\n*/\nfinal class Defaults {\n\n private let "
},
{
"path": "source-cn/structural/flyweight.swift",
"chars": 1271,
"preview": "/*:\n🍃 享元(Flyweight)\n--------------\n\n使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。\n\n### 示例:\n*/\n// "
},
{
"path": "source-cn/structural/header.md",
"chars": 181,
"preview": "\n结构型模式(Structural)\n====================\n\n> 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。\n>\n>**来源:** [维基百科](https://zh.wikip"
},
{
"path": "source-cn/structural/protection_proxy.swift",
"chars": 970,
"preview": "/*:\n☔ 保护代理模式(Protection Proxy)\n------------------\n\n在代理模式中,创建一个类代表另一个底层类的功能。\n保护代理用于限制访问。\n\n### 示例:\n*/\nprotocol DoorOpening"
},
{
"path": "source-cn/structural/virtual_proxy.swift",
"chars": 606,
"preview": "/*:\n🍬 虚拟代理(Virtual Proxy)\n----------------\n\n在代理模式中,创建一个类代表另一个底层类的功能。\n虚拟代理用于对象的需时加载。\n\n### 示例:\n*/\nprotocol HEVSuitMedicalA"
}
]
About this extraction
This page contains the full source code of the ochococo/Design-Patterns-In-Swift GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 99 files (237.5 KB), approximately 63.0k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.