[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: ochococo\n"
  },
  {
    "path": ".github/workflows/generate-playground.yml",
    "content": "name: Generate Playground Files and READMES\n\n# Controls when the action will run. Triggers the workflow on push or pull request\n# events but only for the master branch\non:\n  push:\n    branches: [master]\n\n# A workflow run is made up of one or more jobs that can run sequentially or in parallel\njobs:\n  # This workflow contains a single job called \"build\"\n  generate-playgrounds:\n    # The type of runner that the job will run on\n    runs-on: macos-latest\n\n    # Steps represent a sequence of tasks that will be executed as part of the job\n    steps:\n      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it\n      - uses: actions/checkout@v2\n\n      # Checkout & Generate\n      - name: Generate playgrounds and readmes\n        run: |\n          ./generate-playground.sh\n          ./generate-playground-cn.sh\n\n      # Commit\n      - name: Commit files\n        run: |\n          git config --local user.email \"action@github.com\"\n          git config --local user.name \"GitHub Action\"\n          git add Design-Patterns-CN.playground.zip\n          git add Design-Patterns.playground.zip\n          git add README.md\n          git add README-CN.md\n          git commit -m \"Generate Playground\"\n      ## Push changes to master branch\n      - name: Push changes\n        uses: ad-m/github-push-action@master\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          branch: \"master\"\n          force: false\n\n # This workflow contains a single job called \"build\"\n  generate-chinese-branch:\n    needs: generate-playgrounds\n    # The type of runner that the job will run on\n    runs-on: macos-latest\n\n    # Steps represent a sequence of tasks that will be executed as part of the job\n    steps:\n      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it\n      - uses: actions/checkout@v2\n\n      # Checkout & Generate\n      - name: Generate Chinese Readme\n        run: |\n          ./generate-playground-cn.sh\n          mv ./README-CN.md ./README.md\n\n      # Commit\n      - name: Commit files\n        run: |\n          git config --local user.email \"action@github.com\"\n          git config --local user.name \"GitHub Action\"\n          git add README.md\n          git commit -m \"Generate Chinese version\"\n      ## Push changes to chinese branch\n      - name: Push changes\n        uses: ad-m/github-push-action@master\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          branch: \"chinese\"\n          force: true\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\nUserInterfaceState.xcuserstate\nplayground.xcworkspace\nxcuserdata"
  },
  {
    "path": "CONTRIBUTING-CN.md",
    "content": "如何贡献(中文版)？\n==================\n\n-  你很棒！\n-  仅建议编辑`source-cn`目录中的文件，其余内容是自动生成的并已翻译\n-  提交更改\n-  本地运行`generate-playground-cn.sh`\n-  本地打开`Design-Patterns-CN.playground`文件并检查是否正常运行\n-  删除`generate-playground.sh`引起的更改，不要提交它！（_这是最近的更改_）\n-  请耐心尊重其他贡献者\n\n分支说明\n==================\n\n英文原上游主仓库已与中文版[统一维护](https://github.com/ochococo/Design-Patterns-In-Swift/pull/93)：\n- master 为主维护分支\n- chinese 分支仅为方便展示，将 README.md 显示为中文版本，由 GitHub Action 自动驱动\n\n因此，直接将 PR 提交至[原始仓库](https://github.com/ochococo/Design-Patterns-In-Swift) master 主分支即可。\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "How to contribute?\n==================\n\n- You are awesome!\n- Only editing files inside `source` is recommended, the rest is autogenerated and translated \n- Commit changes\n- Run `generate-playground.sh` locally\n- Open the .playground locally and check if it works\n- Remove the changes caused by `generate-playground.sh`, do not commit it! (_THIS IS A RECENT CHANGE_)\n- Please be patient and respectful to fellow contributors\n"
  },
  {
    "path": "Design-Patterns-CN.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\n 行为型模式\n ========\n \n >在软件工程中， 行为型模式为设计模式的一种类型，用来识别对象之间的常用交流模式并加以实现。如此，可在进行这些交流活动时增强弹性。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n\n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)\n*/\nimport Foundation\n/*:\n🐝 责任链（Chain Of Responsibility）\n------------------------------\n\n责任链模式在面向对象程式设计里是一种软件设计模式，它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象，它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。\n\n### 示例：\n*/\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next = self.next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n/*:\n ### 用法\n */\n// 创建一系列的钱堆，并将其链接起来：10<20<50<100\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// 创建 ATM 实例\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n/*:\n👫 命令（Command）\n ------------\n 命令模式是一种设计模式，它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来，于是这些行动可以被：\n * 重复多次\n * 取消（如果该对象有实现的话）\n * 取消后又再重做\n ### 示例：\n*/\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n/*:\n### 用法\n*/\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n/*:\n🎶 解释器（Interpreter）\n ------------------\n\n 给定一种语言，定义他的文法的一种表示，并定义一个解释器，该解释器使用该表示来解释语言中句子。\n\n ### 示例：\n*/\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n/*:\n### 用法\n*/\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n/*:\n🍫 迭代器（Iterator）\n ---------------\n\n 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。\n \n ### 示例：\n*/\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n/*:\n### 用法\n*/\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n/*:\n💐 中介者（Mediator）\n ---------------\n\n 用一个中介者对象封装一系列的对象交互，中介者使各对象不需要显示地相互作用，从而使耦合松散，而且可以独立地改变它们之间的交互。\n\n ### 示例：\n*/\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n/*:\n### 用法\n*/\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n/*:\n💾 备忘录（Memento）\n--------------\n\n在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态\n\n### 示例：\n*/\ntypealias Memento = [String: String]\n/*:\n发起人（Originator）\n*/\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n/*:\n管理者（Caretaker）\n*/\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n/*:\n### 用法\n*/\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n/*:\n👓 观察者（Observer）\n---------------\n\n一个目标对象管理所有相依于它的观察者对象，并且在它本身的状态改变时主动发出通知\n\n### 示例：\n*/\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n/*:\n### 用法\n*/\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n/*:\n🐉 状态（State）\n---------\n\n在状态模式中，对象的行为是基于它的内部状态而改变的。\n这个模式允许某个类对象在运行时发生改变。\n\n### 示例：\n*/\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n/*:\n### 用法\n*/\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n/*:\n💡 策略（Strategy）\n--------------\n\n对象有某个行为，但是在不同的场景中，该行为有不同的实现算法。策略模式：\n* 定义了一族算法（业务规则）；\n* 封装了每个算法；\n* 这族的算法可互换代替（interchangeable）。\n\n### 示例：\n*/\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n/*:\n ### 用法\n */\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n/*:\n📝 模板方法模式\n-----------\n\n 模板方法模式是一种行为设计模式， 它通过父类/协议中定义了一个算法的框架， 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。\n\n### 示例：\n*/\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n/*:\n### 用法\n*/\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n/*:\n🏃 访问者（Visitor）\n--------------\n\n封装某些作用于某种数据结构中各元素的操作，它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。\n\n### 示例：\n*/\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n/*:\n### 用法\n*/\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n"
  },
  {
    "path": "Design-Patterns-CN.playground/Pages/Creational.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\n 创建型模式\n ========\n \n > 创建型模式是处理对象创建的设计模式，试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题，或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n \n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)\n*/\nimport Foundation\n/*:\n🌰 抽象工厂（Abstract Factory）\n-------------\n\n抽象工厂模式提供了一种方式，可以将一组具有同一主题的单独的工厂封装起来。在正常使用中，客户端程序需要创建抽象工厂的具体实现，然后使用抽象工厂作为接口来创建这一主题的具体对象。\n\n### 示例：\n\n协议\n*/\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// 工厂方法实现\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n/*:\n抽象工厂\n*/\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n/*:\n👷 生成器（Builder）\n--------------\n\n一种对象构建模式。它可以将复杂对象的建造过程抽象出来（抽象类别），使这个抽象过程的不同实现方法可以构造出不同表现（属性）的对象。\n\n### 示例：\n*/\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n/*:\n### 用法\n*/\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n/*:\n🏭 工厂方法（Factory Method）\n-----------------------\n\n定义一个创建对象的接口，但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。\n\n### 示例：\n*/\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n/*:\n### 用法\n*/\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n/*:\n 🔂 单态（Monostate）\n ------------\n\n  单态模式是实现单一共享的另一种方法。不同于单例模式，它通过完全不同的机制，在不限制构造方法的情况下实现单一共享特性。\n  因此，在这种情况下，单态会将状态保存为静态，而不是将整个实例保存为单例。\n [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### 示例:\n*/\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n/*:\n### 用法:\n*/\nimport SwiftUI\n\n// 改变主题\nlet settings = Settings() // 开始使用主题 .old\nsettings.currentTheme = .new // 改变主题为 .new\n\n// 界面一\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// 界面二\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n/*:\n🃏 原型（Prototype）\n--------------\n\n通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”，这个原型是可定制的。\n\n### 示例：\n*/\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n/*:\n### 用法\n*/\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n/*:\n💍 单例（Singleton）\n--------------\n\n单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象，这样有利于我们协调系统整体的行为\n\n### 示例：\n*/\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n/*:\n### 用法\n*/\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n"
  },
  {
    "path": "Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\n设计模式（Swift 5.0 实现）\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).\n\n👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。\n\n🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。\n\n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)\n*/\nimport Foundation\n\nprint(\"您好！\")\n"
  },
  {
    "path": "Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\n结构型模式（Structural）\n====================\n\n> 在软件工程中结构型模式是设计模式，借由一以贯之的方式来了解元件间的关系，以简化设计。\n>\n>**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n\n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)\n*/\nimport Foundation\n/*:\n🔌 适配器（Adapter）\n--------------\n\n适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起，做法是将类自己的接口包裹在一个已存在的类中。\n\n### 示例：\n*/\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n/*:\n**被适配者**\n*/\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n/*:\n**适配器**\n*/\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n/*:\n### 用法\n*/\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n/*:\n🌉 桥接（Bridge）\n-----------\n\n桥接模式将抽象部分与实现部分分离，使它们都可以独立的变化。\n\n### 示例：\n*/\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n/*:\n### 用法\n*/\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n/*:\n🌿 组合（Composite）\n--------------\n\n将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。\n\n### 示例：\n\n组件（Component）\n*/\nprotocol Shape {\n    func draw(fillColor: String)\n}\n/*:\n叶子节点（Leafs）\n*/\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n/*:\n组合\n*/\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n/*:\n### 用法\n*/\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n/*:\n🍧 修饰（Decorator）\n--------------\n\n修饰模式，是面向对象编程领域中，一种动态地往一个类中添加新的行为的设计模式。\n就功能而言，修饰模式相比生成子类更为灵活，这样可以给某个对象而不是整个类添加一些功能。\n\n### 示例：\n*/\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n/*:\n### 用法\n*/\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n/*:\n🎁 外观（Facade）\n-----------\n\n外观模式为子系统中的一组接口提供一个统一的高层接口，使得子系统更容易使用。\n\n### 示例：\n*/\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n/*:\n🍃 享元（Flyweight）\n--------------\n\n使用共享物件，用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件；它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。\n\n### 示例：\n*/\n// 特指咖啡生成的对象会是享元\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// 菜单充当特制咖啡享元对象的工厂和缓存\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n/*:\n☔ 保护代理模式（Protection Proxy）\n------------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n保护代理用于限制访问。\n\n### 示例：\n*/\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n/*:\n### 用法\n*/\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n/*:\n🍬 虚拟代理（Virtual Proxy）\n----------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n虚拟代理用于对象的需时加载。\n\n### 示例：\n*/\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n/*:\n### 用法\n*/\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n"
  },
  {
    "path": "Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline",
    "content": "<?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",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='6.0' target-platform='ios' display-mode='rendered'>\n    <pages>\n        <page name='Index'/>\n        <page name='Behavioral'/>\n        <page name='Creational'/>\n        <page name='Structural'/>\n    </pages>\n</playground>"
  },
  {
    "path": "Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\nBehavioral\n==========\n\n>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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)\n\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n\n*/\nimport Foundation\n/*:\n🐝 Chain Of Responsibility\n--------------------------\n\nThe chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.\n\n### Example:\n*/\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next = self.next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n/*:\n### Usage\n*/\n// Create piles of money and link them together 10 < 20 < 50 < 100.**\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// Build ATM.\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n/*:\n👫 Command\n----------\n\nThe 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.\n\n### Example:\n*/\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n/*:\n### Usage:\n*/\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n/*:\n🎶 Interpreter\n--------------\n\nThe interpreter pattern is used to evaluate sentences in a language.\n\n### Example\n*/\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n/*:\n### Usage\n*/\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n/*:\n🍫 Iterator\n-----------\n\nThe 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.\n\n### Example:\n*/\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n/*:\n### Usage\n*/\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n/*:\n💐 Mediator\n-----------\n\nThe 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.\n\n### Example\n*/\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n/*:\n### Usage\n*/\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n/*:\n💾 Memento\n----------\n\nThe 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.\n\n### Example\n*/\ntypealias Memento = [String: String]\n/*:\nOriginator\n*/\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n/*:\nCaretaker\n*/\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n/*:\n### Usage\n*/\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n/*:\n👓 Observer\n-----------\n\nThe observer pattern is used to allow an object to publish changes to its state.\nOther objects subscribe to be immediately notified of any changes.\n\n### Example\n*/\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n/*:\n### Usage\n*/\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n/*:\n🐉 State\n---------\n\nThe state pattern is used to alter the behaviour of an object as its internal state changes.\nThe pattern allows the class for an object to apparently change at run-time.\n\n### Example\n*/\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n/*:\n### Usage\n*/\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n/*:\n💡 Strategy\n-----------\n\nThe strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.\n\n### Example\n*/\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n/*:\n ### Usage\n */\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n/*:\n📝 Template Method\n-----------\n\n 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.\n\n### Example\n*/\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n/*:\n### Usage\n*/\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n/*:\n🏃 Visitor\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n/*:\n### Usage\n*/\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n"
  },
  {
    "path": "Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\nCreational\n==========\n\n> 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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)\n\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n\n*/\nimport Foundation\n/*:\n🌰 Abstract Factory\n-------------------\n\nThe abstract factory pattern is used to provide a client with a set of related or dependant objects. \nThe \"family\" of objects created by the factory are determined at run-time.\n\n### Example\n\nProtocols\n*/\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// Number implementations with factory methods\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n/*:\nAbstract factory\n*/\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n/*:\n👷 Builder\n----------\n\nThe builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. \nAn external class controls the construction algorithm.\n\n### Example\n*/\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n/*:\n### Usage\n*/\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n/*:\n🏭 Factory Method\n-----------------\n\nThe 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.\n\n### Example\n*/\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n/*:\n### Usage\n*/\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n/*:\n 🔂 Monostate\n ------------\n\n 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. \n So in that case, monostate saves the state as static instead of the entire instance as a singleton.\n [SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### Example:\n*/\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n/*:\n### Usage:\n*/\n\nimport SwiftUI\n\n// When change the theme\nlet settings = Settings() // Starts using theme .old\nsettings.currentTheme = .new // Change theme to .new\n\n// On screen 1\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// On screen 2\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n/*:\n🃏 Prototype\n------------\n\nThe prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. \nThis practise is particularly useful when the construction of a new object is inefficient.\n\n### Example\n*/\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n/*:\n### Usage\n*/\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n/*:\n💍 Singleton\n------------\n\nThe singleton pattern ensures that only one object of a particular class is ever created.\nAll further references to objects of the singleton class refer to the same underlying instance.\nThere are very few applications, do not overuse this pattern!\n\n### Example:\n*/\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n/*:\n### Usage:\n*/\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n"
  },
  {
    "path": "Design-Patterns.playground/Pages/Index.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA 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)).\n\n### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)\n\n👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)\n\n👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。\n\n🚀 How to generate README, Playground and zip from source: [GENERATE.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/GENERATE.md)\n\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n\n*/\nimport Foundation\n\nprint(\"Welcome!\")\n"
  },
  {
    "path": "Design-Patterns.playground/Pages/Structural.xcplaygroundpage/Contents.swift",
    "content": "/*:\n\nStructural\n==========\n\n>In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)\n\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n\n*/\nimport Foundation\n/*:\n🔌 Adapter\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n/*:\n**Adaptee**\n*/\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n/*:\n**Adapter**\n*/\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n/*:\n### Usage\n*/\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n/*:\n🌉 Bridge\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n/*:\n### Usage\n*/\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n/*:\n🌿 Composite\n-------------\n\nThe 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.\n\n### Example\n\nComponent\n*/\nprotocol Shape {\n    func draw(fillColor: String)\n}\n/*:\nLeafs\n*/\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n/*:\nComposite\n*/\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n/*:\n### Usage:\n*/\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n/*:\n🍧 Decorator\n------------\n\nThe 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. \nThis provides a flexible alternative to using inheritance to modify behaviour.\n\n### Example\n*/\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n/*:\n### Usage:\n*/\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n/*:\n🎁 Façade\n---------\n\nThe facade pattern is used to define a simplified interface to a more complex subsystem.\n\n### Example\n*/\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n/*:\n## 🍃 Flyweight\nThe flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.\n### Example\n*/\n// Instances of SpecialityCoffee will be the Flyweights\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// Menu acts as a factory and cache for SpecialityCoffee flyweight objects\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n/*:\n☔ Protection Proxy\n------------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. \nProtection proxy is restricting access.\n\n### Example\n*/\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n/*:\n### Usage\n*/\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n/*:\n🍬 Virtual Proxy\n----------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.\nVirtual proxy is used for loading object on demand.\n\n### Example\n*/\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n/*:\n### Usage\n*/\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n"
  },
  {
    "path": "Design-Patterns.playground/Pages/Structural.xcplaygroundpage/timeline.xctimeline",
    "content": "<?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",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='6.0' target-platform='ios' display-mode='rendered'>\n    <pages>\n        <page name='Index'/>\n        <page name='Behavioral'/>\n        <page name='Creational'/>\n        <page name='Structural'/>\n    </pages>\n</playground>"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>."
  },
  {
    "path": "PULL_REQUEST_TEMPLATE.md",
    "content": "- [ ] Read [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md])\n- [ ] Only edited files inside `source` folder (IMPORTANT) and commited them with a meaningful message\n- [ ] Ran `generate-playground.sh`, no errors\n- [ ] Opened playground, it worked fine\n- [ ] Did not commit the changes caused by `generate-playground.sh`\n- [ ] Linked to and/or created issue\n- [ ] Added a description to PR\n"
  },
  {
    "path": "README-CN.md",
    "content": "\n\n设计模式（Swift 5.0 实现）\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).\n\n👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。\n\n🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。\n\n🚀 如何由源代码，并生成 README 与 Playground 产物，请查看：\n- [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)\n- [CONTRIBUTING-CN.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING-CN.md)\n\n\n\n```swift\nprint(\"您好！\")\n```\n\n\n## 目录\n\n| [行为型模式](#行为型模式)                                    | [创建型模式](#创建型模式)                                 | [结构型模式](#结构型模式structural)                          |\n| ------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------------------ |\n| [🐝 责任链 Chain Of Responsibility](#-责任链chain-of-responsibility) | [🌰 抽象工厂 Abstract Factory](#-抽象工厂abstract-factory) | [🔌 适配器 Adapter](#-适配器adapter)                          |\n| [👫 命令 Command](#-命令command)                              | [👷 生成器 Builder](#-生成器builder)                       | [🌉 桥接 Bridge](#-桥接bridge)                                |\n| [🎶 解释器 Interpreter](#-解释器interpreter)                  | [🏭 工厂方法 Factory Method](#-工厂方法factory-method)     | [🌿 组合 Composite](#-组合composite)                          |\n| [🍫 迭代器 Iterator](#-迭代器iterator)                        | [🔂 单态 Monostate](#-单态monostate)                       | [🍧 修饰 Decorator](#-修饰decorator)                          |\n| [💐 中介者 Mediator](#-中介者mediator)                        | [🃏 原型 Prototype](#-原型prototype)                       | [🎁 外观 Façade](#-外观facade)                                |\n| [💾 备忘录 Memento](#-备忘录memento)                          | [💍 单例 Singleton](#-单例singleton)                       | [🍃 享元 Flyweight](#-享元flyweight)                          |\n| [👓 观察者 Observer](#-观察者observer)                        |                                                           | [☔ 保护代理 Protection Proxy](#-保护代理模式protection-proxy) |\n| [🐉 状态 State](#-状态state)                                  |                                                           | [🍬 虚拟代理 Virtual Proxy](#-虚拟代理virtual-proxy)          |\n| [💡 策略 Strategy](#-策略strategy)                            |                                                           |                                                              |\n| [📝 模板方法 Templdate Method](#-template-method)             |                                                           |                                                              |\n| [🏃 访问者 Visitor](#-访问者visitor)                          |                                                           |                                                              |\n\n 行为型模式\n ========\n \n >在软件工程中， 行为型模式为设计模式的一种类型，用来识别对象之间的常用交流模式并加以实现。如此，可在进行这些交流活动时增强弹性。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n\n\n\n\n🐝 责任链（Chain Of Responsibility）\n------------------------------\n\n责任链模式在面向对象程式设计里是一种软件设计模式，它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象，它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。\n\n### 示例：\n\n```swift\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n```\n\n ### 用法\n \n```swift\n// 创建一系列的钱堆，并将其链接起来：10<20<50<100\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// 创建 ATM 实例\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n```\n\n👫 命令（Command）\n ------------\n 命令模式是一种设计模式，它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来，于是这些行动可以被：\n * 重复多次\n * 取消（如果该对象有实现的话）\n * 取消后又再重做\n ### 示例：\n\n```swift\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n```\n\n### 用法\n\n```swift\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n```\n\n🎶 解释器（Interpreter）\n ------------------\n\n 给定一种语言，定义他的文法的一种表示，并定义一个解释器，该解释器使用该表示来解释语言中句子。\n\n ### 示例：\n\n```swift\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n```\n\n### 用法\n\n```swift\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n```\n\n🍫 迭代器（Iterator）\n ---------------\n\n 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。\n \n ### 示例：\n\n```swift\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n```\n\n### 用法\n\n```swift\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n```\n\n💐 中介者（Mediator）\n ---------------\n\n 用一个中介者对象封装一系列的对象交互，中介者使各对象不需要显示地相互作用，从而使耦合松散，而且可以独立地改变它们之间的交互。\n\n ### 示例：\n\n```swift\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n```\n\n### 用法\n\n```swift\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n```\n\n💾 备忘录（Memento）\n--------------\n\n在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态\n\n### 示例：\n\n```swift\ntypealias Memento = [String: String]\n```\n\n发起人（Originator）\n\n```swift\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n```\n\n管理者（Caretaker）\n\n```swift\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n```\n\n### 用法\n\n```swift\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n```\n\n👓 观察者（Observer）\n---------------\n\n一个目标对象管理所有相依于它的观察者对象，并且在它本身的状态改变时主动发出通知\n\n### 示例：\n\n```swift\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n```\n\n### 用法\n\n```swift\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n```\n\n🐉 状态（State）\n---------\n\n在状态模式中，对象的行为是基于它的内部状态而改变的。\n这个模式允许某个类对象在运行时发生改变。\n\n### 示例：\n\n```swift\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n```\n\n### 用法\n\n```swift\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n```\n\n💡 策略（Strategy）\n--------------\n\n对象有某个行为，但是在不同的场景中，该行为有不同的实现算法。策略模式：\n* 定义了一族算法（业务规则）；\n* 封装了每个算法；\n* 这族的算法可互换代替（interchangeable）。\n\n### 示例：\n\n```swift\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n```\n\n ### 用法\n \n```swift\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n```\n\n📝 模板方法模式\n-----------\n\n 模板方法模式是一种行为设计模式， 它通过父类/协议中定义了一个算法的框架， 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。\n\n### 示例：\n\n```swift\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n```\n\n### 用法\n\n```swift\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n```\n\n🏃 访问者（Visitor）\n--------------\n\n封装某些作用于某种数据结构中各元素的操作，它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。\n\n### 示例：\n\n```swift\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n```\n\n### 用法\n\n```swift\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n```\n\n\n 创建型模式\n ========\n \n > 创建型模式是处理对象创建的设计模式，试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题，或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n \n\n\n\n\n🌰 抽象工厂（Abstract Factory）\n-------------\n\n抽象工厂模式提供了一种方式，可以将一组具有同一主题的单独的工厂封装起来。在正常使用中，客户端程序需要创建抽象工厂的具体实现，然后使用抽象工厂作为接口来创建这一主题的具体对象。\n\n### 示例：\n\n协议\n\n```swift\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// 工厂方法实现\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n```\n\n抽象工厂\n\n```swift\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n```\n\n### 用法\n\n```swift\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n```\n\n👷 生成器（Builder）\n--------------\n\n一种对象构建模式。它可以将复杂对象的建造过程抽象出来（抽象类别），使这个抽象过程的不同实现方法可以构造出不同表现（属性）的对象。\n\n### 示例：\n\n```swift\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n```\n\n### 用法\n\n```swift\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n```\n\n🏭 工厂方法（Factory Method）\n-----------------------\n\n定义一个创建对象的接口，但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。\n\n### 示例：\n\n```swift\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n```\n\n### 用法\n\n```swift\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n```\n\n 🔂 单态（Monostate）\n ------------\n\n  单态模式是实现单一共享的另一种方法。不同于单例模式，它通过完全不同的机制，在不限制构造方法的情况下实现单一共享特性。\n  因此，在这种情况下，单态会将状态保存为静态，而不是将整个实例保存为单例。\n [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### 示例:\n\n```swift\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n```\n\n### 用法:\n\n```swift\nimport SwiftUI\n\n// 改变主题\nlet settings = Settings() // 开始使用主题 .old\nsettings.currentTheme = .new // 改变主题为 .new\n\n// 界面一\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// 界面二\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n```\n\n🃏 原型（Prototype）\n--------------\n\n通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”，这个原型是可定制的。\n\n### 示例：\n\n```swift\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n```\n\n### 用法\n\n```swift\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n```\n\n💍 单例（Singleton）\n--------------\n\n单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象，这样有利于我们协调系统整体的行为\n\n### 示例：\n\n```swift\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n```\n\n### 用法\n\n```swift\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n```\n\n\n结构型模式（Structural）\n====================\n\n> 在软件工程中结构型模式是设计模式，借由一以贯之的方式来了解元件间的关系，以简化设计。\n>\n>**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n\n\n\n\n🔌 适配器（Adapter）\n--------------\n\n适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起，做法是将类自己的接口包裹在一个已存在的类中。\n\n### 示例：\n\n```swift\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n```\n\n**被适配者**\n\n```swift\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n```\n\n**适配器**\n\n```swift\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n```\n\n### 用法\n\n```swift\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n```\n\n🌉 桥接（Bridge）\n-----------\n\n桥接模式将抽象部分与实现部分分离，使它们都可以独立的变化。\n\n### 示例：\n\n```swift\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n```\n\n### 用法\n\n```swift\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n```\n\n🌿 组合（Composite）\n--------------\n\n将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。\n\n### 示例：\n\n组件（Component）\n\n```swift\nprotocol Shape {\n    func draw(fillColor: String)\n}\n```\n\n叶子节点（Leafs）\n\n```swift\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n```\n\n组合\n\n```swift\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n```\n\n### 用法\n\n```swift\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n```\n\n🍧 修饰（Decorator）\n--------------\n\n修饰模式，是面向对象编程领域中，一种动态地往一个类中添加新的行为的设计模式。\n就功能而言，修饰模式相比生成子类更为灵活，这样可以给某个对象而不是整个类添加一些功能。\n\n### 示例：\n\n```swift\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n```\n\n### 用法\n\n```swift\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n```\n\n🎁 外观（Facade）\n-----------\n\n外观模式为子系统中的一组接口提供一个统一的高层接口，使得子系统更容易使用。\n\n### 示例：\n\n```swift\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n```\n\n### 用法\n\n```swift\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n```\n\n🍃 享元（Flyweight）\n--------------\n\n使用共享物件，用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件；它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。\n\n### 示例：\n\n```swift\n// 特指咖啡生成的对象会是享元\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// 菜单充当特制咖啡享元对象的工厂和缓存\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n```\n\n### 用法\n\n```swift\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n```\n\n☔ 保护代理模式（Protection Proxy）\n------------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n保护代理用于限制访问。\n\n### 示例：\n\n```swift\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n```\n\n### 用法\n\n```swift\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n```\n\n🍬 虚拟代理（Virtual Proxy）\n----------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n虚拟代理用于对象的需时加载。\n\n### 示例：\n\n```swift\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n```\n\n### 用法\n\n```swift\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n```\n\n\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)\n"
  },
  {
    "path": "README.md",
    "content": "\n\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA 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)).\n\n### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)\n\n👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)\n\n👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。\n\n🚀 How to generate README, Playground and zip from source: [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)\n\n\n```swift\nprint(\"Welcome!\")\n```\n\n\n## Table of Contents\n\n| [Behavioral](#behavioral)                              | [Creational](#creational)                | [Structural](#structural)                |\n| ------------------------------------------------------ | ---------------------------------------- | ---------------------------------------- |\n| [🐝 Chain Of Responsibility](#-chain-of-responsibility) | [🌰 Abstract Factory](#-abstract-factory) | [🔌 Adapter](#-adapter)                   |\n| [👫 Command](#-command)                                 | [👷 Builder](#-builder)                   | [🌉 Bridge](#-bridge)                     |\n| [🎶 Interpreter](#-interpreter)                         | [🏭 Factory Method](#-factory-method)     | [🌿 Composite](#-composite)               |\n| [🍫 Iterator](#-iterator)                               | [🔂 Monostate](#-monostate)               | [🍧 Decorator](#-decorator)               |\n| [💐 Mediator](#-mediator)                               | [🃏 Prototype](#-prototype)               | [🎁 Façade](#-fa-ade)                     |\n| [💾 Memento](#-memento)                                 | [💍 Singleton](#-singleton)               | [🍃 Flyweight](#-flyweight)               |\n| [👓 Observer](#-observer)                               |                                          | [☔ Protection Proxy](#-protection-proxy) |\n| [🐉 State](#-state)                                     |                                          | [🍬 Virtual Proxy](#-virtual-proxy)       |\n| [💡 Strategy](#-strategy)                               |                                          |                                          |\n| [📝 Template Method](#-template-method)                 |                                          |                                          |\n| [🏃 Visitor](#-visitor)                                 |                                          |                                          |\n\nBehavioral\n==========\n\n>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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)\n\n\n\n\n🐝 Chain Of Responsibility\n--------------------------\n\nThe chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.\n\n### Example:\n\n```swift\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n```\n\n### Usage\n\n```swift\n// Create piles of money and link them together 10 < 20 < 50 < 100.**\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// Build ATM.\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n```\n\n👫 Command\n----------\n\nThe 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.\n\n### Example:\n\n```swift\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n```\n\n### Usage:\n\n```swift\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n```\n\n🎶 Interpreter\n--------------\n\nThe interpreter pattern is used to evaluate sentences in a language.\n\n### Example\n\n```swift\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n```\n\n### Usage\n\n```swift\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n```\n\n🍫 Iterator\n-----------\n\nThe 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.\n\n### Example:\n\n```swift\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n```\n\n### Usage\n\n```swift\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n```\n\n💐 Mediator\n-----------\n\nThe 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.\n\n### Example\n\n```swift\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n```\n\n### Usage\n\n```swift\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n```\n\n💾 Memento\n----------\n\nThe 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.\n\n### Example\n\n```swift\ntypealias Memento = [String: String]\n```\n\nOriginator\n\n```swift\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n```\n\nCaretaker\n\n```swift\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n```\n\n### Usage\n\n```swift\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n```\n\n👓 Observer\n-----------\n\nThe observer pattern is used to allow an object to publish changes to its state.\nOther objects subscribe to be immediately notified of any changes.\n\n### Example\n\n```swift\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n```\n\n### Usage\n\n```swift\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n```\n\n🐉 State\n---------\n\nThe state pattern is used to alter the behaviour of an object as its internal state changes.\nThe pattern allows the class for an object to apparently change at run-time.\n\n### Example\n\n```swift\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n```\n\n### Usage\n\n```swift\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n```\n\n💡 Strategy\n-----------\n\nThe strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.\n\n### Example\n\n```swift\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n```\n\n ### Usage\n \n```swift\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n```\n\n📝 Template Method\n-----------\n\n 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.\n\n### Example\n\n```swift\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n```\n\n### Usage\n\n```swift\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n```\n\n🏃 Visitor\n----------\n\nThe 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.\n\n### Example\n\n```swift\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n```\n\n### Usage\n\n```swift\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n```\n\n\nCreational\n==========\n\n> 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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)\n\n\n\n\n🌰 Abstract Factory\n-------------------\n\nThe abstract factory pattern is used to provide a client with a set of related or dependant objects. \nThe \"family\" of objects created by the factory are determined at run-time.\n\n### Example\n\nProtocols\n\n```swift\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// Number implementations with factory methods\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n```\n\nAbstract factory\n\n```swift\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n```\n\n### Usage\n\n```swift\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n```\n\n👷 Builder\n----------\n\nThe builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. \nAn external class controls the construction algorithm.\n\n### Example\n\n```swift\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n```\n\n### Usage\n\n```swift\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n```\n\n🏭 Factory Method\n-----------------\n\nThe 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.\n\n### Example\n\n```swift\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n```\n\n### Usage\n\n```swift\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n```\n\n 🔂 Monostate\n ------------\n\n 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. \n So in that case, monostate saves the state as static instead of the entire instance as a singleton.\n [SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### Example:\n\n```swift\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n```\n\n### Usage:\n\n```swift\n\nimport SwiftUI\n\n// When change the theme\nlet settings = Settings() // Starts using theme .old\nsettings.currentTheme = .new // Change theme to .new\n\n// On screen 1\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// On screen 2\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n```\n\n🃏 Prototype\n------------\n\nThe prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. \nThis practise is particularly useful when the construction of a new object is inefficient.\n\n### Example\n\n```swift\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n```\n\n### Usage\n\n```swift\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n```\n\n💍 Singleton\n------------\n\nThe singleton pattern ensures that only one object of a particular class is ever created.\nAll further references to objects of the singleton class refer to the same underlying instance.\nThere are very few applications, do not overuse this pattern!\n\n### Example:\n\n```swift\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n```\n\n### Usage:\n\n```swift\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n```\n\n\nStructural\n==========\n\n>In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)\n\n\n\n\n🔌 Adapter\n----------\n\nThe 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.\n\n### Example\n\n```swift\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n```\n\n**Adaptee**\n\n```swift\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n```\n\n**Adapter**\n\n```swift\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n```\n\n### Usage\n\n```swift\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n```\n\n🌉 Bridge\n----------\n\nThe 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.\n\n### Example\n\n```swift\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n```\n\n### Usage\n\n```swift\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n```\n\n🌿 Composite\n-------------\n\nThe 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.\n\n### Example\n\nComponent\n\n```swift\nprotocol Shape {\n    func draw(fillColor: String)\n}\n```\n\nLeafs\n\n```swift\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n```\n\nComposite\n\n```swift\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n```\n\n### Usage:\n\n```swift\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n```\n\n🍧 Decorator\n------------\n\nThe 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. \nThis provides a flexible alternative to using inheritance to modify behaviour.\n\n### Example\n\n```swift\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n```\n\n### Usage:\n\n```swift\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n```\n\n🎁 Façade\n---------\n\nThe facade pattern is used to define a simplified interface to a more complex subsystem.\n\n### Example\n\n```swift\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n```\n\n### Usage\n\n```swift\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n```\n\n## 🍃 Flyweight\nThe flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.\n### Example\n\n```swift\n// Instances of SpecialityCoffee will be the Flyweights\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// Menu acts as a factory and cache for SpecialityCoffee flyweight objects\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n```\n\n### Usage\n\n```swift\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n```\n\n☔ Protection Proxy\n------------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. \nProtection proxy is restricting access.\n\n### Example\n\n```swift\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n```\n\n### Usage\n\n```swift\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n```\n\n🍬 Virtual Proxy\n----------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.\nVirtual proxy is used for loading object on demand.\n\n### Example\n\n```swift\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n```\n\n### Usage\n\n```swift\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n```\n\n\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)\n"
  },
  {
    "path": "generate-playground-cn.sh",
    "content": "#!/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 love to rewrite it in Swift soon.\n\ncombineSwiftCN() {\n\tcat source-cn/startComment > $2\n\tcat $1/header.md  >> $2\n\tcat source-cn/contents.md  >> $2\n\tcat source-cn/endComment >> $2\n\tcat source-cn/imports.swift >> $2\n\tcat $1/*.swift >> $2\n\t{ rm $2 && awk '{gsub(\"\\\\*//\\\\*:\", \"\", $0); print}' > $2; } < $2\n}\n\nmove() {\n\tmv $1.swift Design-Patterns-CN.playground/Pages/$1.xcplaygroundpage/Contents.swift\n}\n\nplayground() {\n\tcombineSwiftCN source-cn/$1 $1.swift \n\tmove $1\n}\n\ncombineMarkdown() {\n\tcat $1/header.md  > $2\n\n\t{ rm $2 && awk '{gsub(\"\\\\*/\", \"\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"/\\\\*:\", \"\", $0); print}' > $2; } < $2\n\n\tcat source-cn/startSwiftCode >> $2\n\tcat $1/*.swift >> $2\n\n\t{ rm $2 && awk '{gsub(\"\\\\*//\\\\*:\", \"\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"\\\\*/\", \"\\n```swift\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"/\\\\*:\", \"```\\n\", $0); print}' > $2; } < $2\n\t\n\tcat source-cn/endSwiftCode >> $2\n\n\t{ rm $2 && awk '{gsub(\"```swift```\", \"\", $0); print}' > $2; } < $2\n\n\tcat $2 >> README-CN.md\n\trm $2\n}\n\nreadme() {\n\tcombineMarkdown source-cn/$1 $1.md\n}\n\nplayground Index\nplayground Behavioral\nplayground Creational\nplayground Structural\n\nzip -r -X Design-Patterns-CN.playground.zip ./Design-Patterns-CN.playground\n\necho \"\" > README-CN.md\n\nreadme Index\ncat source-cn/contentsReadme.md >> README-CN.md\nreadme Behavioral\nreadme Creational\nreadme Structural\ncat source-cn/footer.md  >> README-CN.md"
  },
  {
    "path": "generate-playground.sh",
    "content": "#!/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 love to rewrite it in Swift soon.\n\ncombineSwift() {\n\tcat source/startComment > $2\n\tcat $1/header.md  >> $2\n\tcat source/contents.md  >> $2\n\tcat source/endComment >> $2\n\tcat source/imports.swift >> $2\n\tcat $1/*.swift >> $2\n\t{ rm $2 && awk '{gsub(\"\\\\*//\\\\*:\", \"\", $0); print}' > $2; } < $2\n}\n\nmove() {\n\tmv $1.swift Design-Patterns.playground/Pages/$1.xcplaygroundpage/Contents.swift\n}\n\nplayground() {\n\tcombineSwift source/$1 $1.swift \n\tmove $1\n}\n\ncombineMarkdown() {\n\tcat $1/header.md  > $2\n\n\t{ rm $2 && awk '{gsub(\"\\\\*/\", \"\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"/\\\\*:\", \"\", $0); print}' > $2; } < $2\n\n\tcat source/startSwiftCode >> $2\n\tcat $1/*.swift >> $2\n\n\t{ rm $2 && awk '{gsub(\"\\\\*//\\\\*:\", \"\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"\\\\*/\", \"\\n```swift\", $0); print}' > $2; } < $2\n\t{ rm $2 && awk '{gsub(\"/\\\\*:\", \"```\\n\", $0); print}' > $2; } < $2\n\t\n\tcat source/endSwiftCode >> $2\n\n\t{ rm $2 && awk '{gsub(\"```swift```\", \"\", $0); print}' > $2; } < $2\n\n\tcat $2 >> README.md\n\trm $2\n}\n\nreadme() {\n\tcombineMarkdown source/$1 $1.md\n}\n\nplayground Index\nplayground Behavioral\nplayground Creational\nplayground Structural\n\nzip -r -X Design-Patterns.playground.zip ./Design-Patterns.playground\n\necho \"\" > README.md\n\nreadme Index\ncat source/contentsReadme.md >> README.md\nreadme Behavioral\nreadme Creational\nreadme Structural\ncat source/footer.md  >> README.md"
  },
  {
    "path": "source/Index/header.md",
    "content": "\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA 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)).\n\n### [🇨🇳中文版](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/README-CN.md)\n\n👷 Project started by: [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki)\n\n👷 中文版由 [@binglogo](https://twitter.com/binglogo) (棒棒彬) 整理翻译。\n\n🚀 How to generate README, Playground and zip from source: [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)\n"
  },
  {
    "path": "source/Index/welcome.swift",
    "content": "\nprint(\"Welcome!\")\n"
  },
  {
    "path": "source/behavioral/chain_of_responsibility.swift",
    "content": "/*:\n🐝 Chain Of Responsibility\n--------------------------\n\nThe chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.\n\n### Example:\n*/\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n/*:\n### Usage\n*/\n// Create piles of money and link them together 10 < 20 < 50 < 100.**\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// Build ATM.\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n"
  },
  {
    "path": "source/behavioral/command.swift",
    "content": "/*:\n👫 Command\n----------\n\nThe 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.\n\n### Example:\n*/\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n/*:\n### Usage:\n*/\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n"
  },
  {
    "path": "source/behavioral/header.md",
    "content": "\nBehavioral\n==========\n\n>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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern)\n"
  },
  {
    "path": "source/behavioral/interpreter.swift",
    "content": "/*:\n🎶 Interpreter\n--------------\n\nThe interpreter pattern is used to evaluate sentences in a language.\n\n### Example\n*/\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n/*:\n### Usage\n*/\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n"
  },
  {
    "path": "source/behavioral/iterator.swift",
    "content": "/*:\n🍫 Iterator\n-----------\n\nThe 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.\n\n### Example:\n*/\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n/*:\n### Usage\n*/\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n"
  },
  {
    "path": "source/behavioral/mediator.swift",
    "content": "/*:\n💐 Mediator\n-----------\n\nThe 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.\n\n### Example\n*/\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n/*:\n### Usage\n*/\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n"
  },
  {
    "path": "source/behavioral/memento.swift",
    "content": "/*:\n💾 Memento\n----------\n\nThe 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.\n\n### Example\n*/\ntypealias Memento = [String: String]\n/*:\nOriginator\n*/\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n/*:\nCaretaker\n*/\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n/*:\n### Usage\n*/\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n"
  },
  {
    "path": "source/behavioral/observer.swift",
    "content": "/*:\n👓 Observer\n-----------\n\nThe observer pattern is used to allow an object to publish changes to its state.\nOther objects subscribe to be immediately notified of any changes.\n\n### Example\n*/\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n/*:\n### Usage\n*/\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n"
  },
  {
    "path": "source/behavioral/state.swift",
    "content": "/*:\n🐉 State\n---------\n\nThe state pattern is used to alter the behaviour of an object as its internal state changes.\nThe pattern allows the class for an object to apparently change at run-time.\n\n### Example\n*/\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n/*:\n### Usage\n*/\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n"
  },
  {
    "path": "source/behavioral/strategy.swift",
    "content": "/*:\n💡 Strategy\n-----------\n\nThe strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.\n\n### Example\n*/\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n/*:\n ### Usage\n */\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n"
  },
  {
    "path": "source/behavioral/template_method.swift",
    "content": "/*:\n📝 Template Method\n-----------\n\n 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.\n\n### Example\n*/\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n/*:\n### Usage\n*/\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n"
  },
  {
    "path": "source/behavioral/visitor.swift",
    "content": "/*:\n🏃 Visitor\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n/*:\n### Usage\n*/\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n"
  },
  {
    "path": "source/contents.md",
    "content": "\n## Table of Contents\n\n* [Behavioral](Behavioral)\n* [Creational](Creational)\n* [Structural](Structural)\n"
  },
  {
    "path": "source/contentsReadme.md",
    "content": "\n## Table of Contents\n\n| [Behavioral](#behavioral)                              | [Creational](#creational)                | [Structural](#structural)                |\n| ------------------------------------------------------ | ---------------------------------------- | ---------------------------------------- |\n| [🐝 Chain Of Responsibility](#-chain-of-responsibility) | [🌰 Abstract Factory](#-abstract-factory) | [🔌 Adapter](#-adapter)                   |\n| [👫 Command](#-command)                                 | [👷 Builder](#-builder)                   | [🌉 Bridge](#-bridge)                     |\n| [🎶 Interpreter](#-interpreter)                         | [🏭 Factory Method](#-factory-method)     | [🌿 Composite](#-composite)               |\n| [🍫 Iterator](#-iterator)                               | [🔂 Monostate](#-monostate)               | [🍧 Decorator](#-decorator)               |\n| [💐 Mediator](#-mediator)                               | [🃏 Prototype](#-prototype)               | [🎁 Façade](#-fa-ade)                     |\n| [💾 Memento](#-memento)                                 | [💍 Singleton](#-singleton)               | [🍃 Flyweight](#-flyweight)               |\n| [👓 Observer](#-observer)                               |                                          | [☔ Protection Proxy](#-protection-proxy) |\n| [🐉 State](#-state)                                     |                                          | [🍬 Virtual Proxy](#-virtual-proxy)       |\n| [💡 Strategy](#-strategy)                               |                                          |                                          |\n| [📝 Template Method](#-template-method)                 |                                          |                                          |\n| [🏃 Visitor](#-visitor)                                 |                                          |                                          |\n"
  },
  {
    "path": "source/creational/abstract_factory.swift",
    "content": "/*:\n🌰 Abstract Factory\n-------------------\n\nThe abstract factory pattern is used to provide a client with a set of related or dependant objects. \nThe \"family\" of objects created by the factory are determined at run-time.\n\n### Example\n\nProtocols\n*/\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// Number implementations with factory methods\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n/*:\nAbstract factory\n*/\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n"
  },
  {
    "path": "source/creational/builder.swift",
    "content": "/*:\n👷 Builder\n----------\n\nThe builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. \nAn external class controls the construction algorithm.\n\n### Example\n*/\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n/*:\n### Usage\n*/\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n"
  },
  {
    "path": "source/creational/factory.swift",
    "content": "/*:\n🏭 Factory Method\n-----------------\n\nThe 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.\n\n### Example\n*/\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n/*:\n### Usage\n*/\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n"
  },
  {
    "path": "source/creational/header.md",
    "content": "\nCreational\n==========\n\n> 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.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)\n"
  },
  {
    "path": "source/creational/monostate.swift",
    "content": "/*:\n 🔂 Monostate\n ------------\n\n 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. \n So in that case, monostate saves the state as static instead of the entire instance as a singleton.\n [SINGLETON and MONOSTATE - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### Example:\n*/\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n/*:\n### Usage:\n*/\n\nimport SwiftUI\n\n// When change the theme\nlet settings = Settings() // Starts using theme .old\nsettings.currentTheme = .new // Change theme to .new\n\n// On screen 1\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// On screen 2\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n"
  },
  {
    "path": "source/creational/prototype.swift",
    "content": "/*:\n🃏 Prototype\n------------\n\nThe prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. \nThis practise is particularly useful when the construction of a new object is inefficient.\n\n### Example\n*/\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n/*:\n### Usage\n*/\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n"
  },
  {
    "path": "source/creational/singleton.swift",
    "content": "/*:\n💍 Singleton\n------------\n\nThe singleton pattern ensures that only one object of a particular class is ever created.\nAll further references to objects of the singleton class refer to the same underlying instance.\nThere are very few applications, do not overuse this pattern!\n\n### Example:\n*/\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n/*:\n### Usage:\n*/\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n"
  },
  {
    "path": "source/endComment",
    "content": "\n*/"
  },
  {
    "path": "source/endSwiftCode",
    "content": "```\n\n"
  },
  {
    "path": "source/footer.md",
    "content": "\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)\n"
  },
  {
    "path": "source/imports.swift",
    "content": "\nimport Foundation\n"
  },
  {
    "path": "source/startComment",
    "content": "/*:\n"
  },
  {
    "path": "source/startSwiftCode",
    "content": "\n\n```swift"
  },
  {
    "path": "source/structural/adapter.swift",
    "content": "/*:\n🔌 Adapter\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n/*:\n**Adaptee**\n*/\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n/*:\n**Adapter**\n*/\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n/*:\n### Usage\n*/\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n"
  },
  {
    "path": "source/structural/bridge.swift",
    "content": "/*:\n🌉 Bridge\n----------\n\nThe 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.\n\n### Example\n*/\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n/*:\n### Usage\n*/\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n"
  },
  {
    "path": "source/structural/composite.swift",
    "content": "/*:\n🌿 Composite\n-------------\n\nThe 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.\n\n### Example\n\nComponent\n*/\nprotocol Shape {\n    func draw(fillColor: String)\n}\n/*:\nLeafs\n*/\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n/*:\nComposite\n*/\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n/*:\n### Usage:\n*/\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n"
  },
  {
    "path": "source/structural/decorator.swift",
    "content": "/*:\n🍧 Decorator\n------------\n\nThe 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. \nThis provides a flexible alternative to using inheritance to modify behaviour.\n\n### Example\n*/\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n/*:\n### Usage:\n*/\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n"
  },
  {
    "path": "source/structural/facade.swift",
    "content": "/*:\n🎁 Façade\n---------\n\nThe facade pattern is used to define a simplified interface to a more complex subsystem.\n\n### Example\n*/\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n"
  },
  {
    "path": "source/structural/flyweight.swift",
    "content": "/*:\n## 🍃 Flyweight\nThe flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.\n### Example\n*/\n// Instances of SpecialityCoffee will be the Flyweights\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// Menu acts as a factory and cache for SpecialityCoffee flyweight objects\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n/*:\n### Usage\n*/\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n"
  },
  {
    "path": "source/structural/header.md",
    "content": "\nStructural\n==========\n\n>In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.\n>\n>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern)\n"
  },
  {
    "path": "source/structural/protection_proxy.swift",
    "content": "/*:\n☔ Protection Proxy\n------------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. \nProtection proxy is restricting access.\n\n### Example\n*/\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n/*:\n### Usage\n*/\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n"
  },
  {
    "path": "source/structural/virtual_proxy.swift",
    "content": "/*:\n🍬 Virtual Proxy\n----------------\n\nThe proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object.\nVirtual proxy is used for loading object on demand.\n\n### Example\n*/\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n/*:\n### Usage\n*/\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n"
  },
  {
    "path": "source-cn/Index/header.md",
    "content": "\n设计模式（Swift 5.0 实现）\n======================\n\n([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).\n\n👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。\n\n🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。\n\n🚀 如何由源代码，并生成 README 与 Playground 产物，请查看：\n- [CONTRIBUTING.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING.md)\n- [CONTRIBUTING-CN.md](https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/CONTRIBUTING-CN.md)\n\n"
  },
  {
    "path": "source-cn/Index/welcome.swift",
    "content": "\nprint(\"您好！\")\n"
  },
  {
    "path": "source-cn/behavioral/chain_of_responsibility.swift",
    "content": "/*:\n🐝 责任链（Chain Of Responsibility）\n------------------------------\n\n责任链模式在面向对象程式设计里是一种软件设计模式，它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象，它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。\n\n### 示例：\n*/\n\nprotocol Withdrawing {\n    func withdraw(amount: Int) -> Bool\n}\n\nfinal class MoneyPile: Withdrawing {\n\n    let value: Int\n    var quantity: Int\n    var next: Withdrawing?\n\n    init(value: Int, quantity: Int, next: Withdrawing?) {\n        self.value = value\n        self.quantity = quantity\n        self.next = next\n    }\n\n    func withdraw(amount: Int) -> Bool {\n\n        var amount = amount\n\n        func canTakeSomeBill(want: Int) -> Bool {\n            return (want / self.value) > 0\n        }\n\n        var quantity = self.quantity\n\n        while canTakeSomeBill(want: amount) {\n\n            if quantity == 0 {\n                break\n            }\n\n            amount -= self.value\n            quantity -= 1\n        }\n\n        guard amount > 0 else {\n            return true\n        }\n\n        if let next {\n            return next.withdraw(amount: amount)\n        }\n\n        return false\n    }\n}\n\nfinal class ATM: Withdrawing {\n\n    private var hundred: Withdrawing\n    private var fifty: Withdrawing\n    private var twenty: Withdrawing\n    private var ten: Withdrawing\n\n    private var startPile: Withdrawing {\n        return self.hundred\n    }\n\n    init(hundred: Withdrawing,\n           fifty: Withdrawing,\n          twenty: Withdrawing,\n             ten: Withdrawing) {\n\n        self.hundred = hundred\n        self.fifty = fifty\n        self.twenty = twenty\n        self.ten = ten\n    }\n\n    func withdraw(amount: Int) -> Bool {\n        return startPile.withdraw(amount: amount)\n    }\n}\n/*:\n ### 用法\n */\n// 创建一系列的钱堆，并将其链接起来：10<20<50<100\nlet ten = MoneyPile(value: 10, quantity: 6, next: nil)\nlet twenty = MoneyPile(value: 20, quantity: 2, next: ten)\nlet fifty = MoneyPile(value: 50, quantity: 2, next: twenty)\nlet hundred = MoneyPile(value: 100, quantity: 1, next: fifty)\n\n// 创建 ATM 实例\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) // Cannot because ATM has only 300\natm.withdraw(amount: 100) // Can withdraw - 1x100\n"
  },
  {
    "path": "source-cn/behavioral/command.swift",
    "content": "/*:\n👫 命令（Command）\n ------------\n 命令模式是一种设计模式，它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来，于是这些行动可以被：\n * 重复多次\n * 取消（如果该对象有实现的话）\n * 取消后又再重做\n ### 示例：\n*/\nprotocol DoorCommand {\n    func execute() -> String\n}\n\nfinal class OpenCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Opened \\(doors)\"\n    }\n}\n\nfinal class CloseCommand: DoorCommand {\n    let doors:String\n\n    required init(doors: String) {\n        self.doors = doors\n    }\n    \n    func execute() -> String {\n        return \"Closed \\(doors)\"\n    }\n}\n\nfinal class HAL9000DoorsOperations {\n    let openCommand: DoorCommand\n    let closeCommand: DoorCommand\n    \n    init(doors: String) {\n        self.openCommand = OpenCommand(doors:doors)\n        self.closeCommand = CloseCommand(doors:doors)\n    }\n    \n    func close() -> String {\n        return closeCommand.execute()\n    }\n    \n    func open() -> String {\n        return openCommand.execute()\n    }\n}\n/*:\n### 用法\n*/\nlet podBayDoors = \"Pod Bay Doors\"\nlet doorModule = HAL9000DoorsOperations(doors:podBayDoors)\n\ndoorModule.open()\ndoorModule.close()\n"
  },
  {
    "path": "source-cn/behavioral/header.md",
    "content": "\n 行为型模式\n ========\n \n >在软件工程中， 行为型模式为设计模式的一种类型，用来识别对象之间的常用交流模式并加以实现。如此，可在进行这些交流活动时增强弹性。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E8%A1%8C%E7%82%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n"
  },
  {
    "path": "source-cn/behavioral/interpreter.swift",
    "content": "/*:\n🎶 解释器（Interpreter）\n ------------------\n\n 给定一种语言，定义他的文法的一种表示，并定义一个解释器，该解释器使用该表示来解释语言中句子。\n\n ### 示例：\n*/\n\nprotocol IntegerExpression {\n    func evaluate(_ context: IntegerContext) -> Int\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression\n    func copied() -> IntegerExpression\n}\n\nfinal class IntegerContext {\n    private var data: [Character:Int] = [:]\n\n    func lookup(name: Character) -> Int {\n        return self.data[name]!\n    }\n\n    func assign(expression: IntegerVariableExpression, value: Int) {\n        self.data[expression.name] = value\n    }\n}\n\nfinal class IntegerVariableExpression: IntegerExpression {\n    let name: Character\n\n    init(name: Character) {\n        self.name = name\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return context.lookup(name: self.name)\n    }\n\n    func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        if name == self.name {\n            return integerExpression.copied()\n        } else {\n            return IntegerVariableExpression(name: self.name)\n        }\n    }\n\n    func copied() -> IntegerExpression {\n        return IntegerVariableExpression(name: self.name)\n    }\n}\n\nfinal class AddExpression: IntegerExpression {\n    private var operand1: IntegerExpression\n    private var operand2: IntegerExpression\n\n    init(op1: IntegerExpression, op2: IntegerExpression) {\n        self.operand1 = op1\n        self.operand2 = op2\n    }\n\n    func evaluate(_ context: IntegerContext) -> Int {\n        return self.operand1.evaluate(context) + self.operand2.evaluate(context)\n    }\n\n    func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {\n        return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),\n                             op2: operand2.replace(character: character, integerExpression: integerExpression))\n    }\n\n    func copied() -> IntegerExpression {\n        return AddExpression(op1: self.operand1, op2: self.operand2)\n    }\n}\n/*:\n### 用法\n*/\nvar context = IntegerContext()\n\nvar a = IntegerVariableExpression(name: \"A\")\nvar b = IntegerVariableExpression(name: \"B\")\nvar c = IntegerVariableExpression(name: \"C\")\n\nvar expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)\n\ncontext.assign(expression: a, value: 2)\ncontext.assign(expression: b, value: 1)\ncontext.assign(expression: c, value: 3)\n\nvar result = expression.evaluate(context)\n"
  },
  {
    "path": "source-cn/behavioral/iterator.swift",
    "content": "/*:\n🍫 迭代器（Iterator）\n ---------------\n\n 迭代器模式可以让用户通过特定的接口巡访容器中的每一个元素而不用了解底层的实现。\n \n ### 示例：\n*/\nstruct Novella {\n    let name: String\n}\n\nstruct Novellas {\n    let novellas: [Novella]\n}\n\nstruct NovellasIterator: IteratorProtocol {\n\n    private var current = 0\n    private let novellas: [Novella]\n\n    init(novellas: [Novella]) {\n        self.novellas = novellas\n    }\n\n    mutating func next() -> Novella? {\n        defer { current += 1 }\n        return novellas.count > current ? novellas[current] : nil\n    }\n}\n\nextension Novellas: Sequence {\n    func makeIterator() -> NovellasIterator {\n        return NovellasIterator(novellas: novellas)\n    }\n}\n/*:\n### 用法\n*/\nlet greatNovellas = Novellas(novellas: [Novella(name: \"The Mist\")] )\n\nfor novella in greatNovellas {\n    print(\"I've read: \\(novella)\")\n}\n"
  },
  {
    "path": "source-cn/behavioral/mediator.swift",
    "content": "/*:\n💐 中介者（Mediator）\n ---------------\n\n 用一个中介者对象封装一系列的对象交互，中介者使各对象不需要显示地相互作用，从而使耦合松散，而且可以独立地改变它们之间的交互。\n\n ### 示例：\n*/\nprotocol Receiver {\n    associatedtype MessageType\n    func receive(message: MessageType)\n}\n\nprotocol Sender {\n    associatedtype MessageType\n    associatedtype ReceiverType: Receiver\n    \n    var recipients: [ReceiverType] { get }\n    \n    func send(message: MessageType)\n}\n\nstruct Programmer: Receiver {\n    let name: String\n    \n    init(name: String) {\n        self.name = name\n    }\n    \n    func receive(message: String) {\n        print(\"\\(name) received: \\(message)\")\n    }\n}\n\nfinal class MessageMediator: Sender {\n    internal var recipients: [Programmer] = []\n    \n    func add(recipient: Programmer) {\n        recipients.append(recipient)\n    }\n    \n    func send(message: String) {\n        for recipient in recipients {\n            recipient.receive(message: message)\n        }\n    }\n}\n\n/*:\n### 用法\n*/\nfunc spamMonster(message: String, worker: MessageMediator) {\n    worker.send(message: message)\n}\n\nlet messagesMediator = MessageMediator()\n\nlet user0 = Programmer(name: \"Linus Torvalds\")\nlet user1 = Programmer(name: \"Avadis 'Avie' Tevanian\")\nmessagesMediator.add(recipient: user0)\nmessagesMediator.add(recipient: user1)\n\nspamMonster(message: \"I'd Like to Add you to My Professional Network\", worker: messagesMediator)\n\n"
  },
  {
    "path": "source-cn/behavioral/memento.swift",
    "content": "/*:\n💾 备忘录（Memento）\n--------------\n\n在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态\n\n### 示例：\n*/\ntypealias Memento = [String: String]\n/*:\n发起人（Originator）\n*/\nprotocol MementoConvertible {\n    var memento: Memento { get }\n    init?(memento: Memento)\n}\n\nstruct GameState: MementoConvertible {\n\n    private enum Keys {\n        static let chapter = \"com.valve.halflife.chapter\"\n        static let weapon = \"com.valve.halflife.weapon\"\n    }\n\n    var chapter: String\n    var weapon: String\n\n    init(chapter: String, weapon: String) {\n        self.chapter = chapter\n        self.weapon = weapon\n    }\n\n    init?(memento: Memento) {\n        guard let mementoChapter = memento[Keys.chapter],\n              let mementoWeapon = memento[Keys.weapon] else {\n            return nil\n        }\n\n        chapter = mementoChapter\n        weapon = mementoWeapon\n    }\n\n    var memento: Memento {\n        return [ Keys.chapter: chapter, Keys.weapon: weapon ]\n    }\n}\n/*:\n管理者（Caretaker）\n*/\nenum CheckPoint {\n\n    private static let defaults = UserDefaults.standard\n\n    static func save(_ state: MementoConvertible, saveName: String) {\n        defaults.set(state.memento, forKey: saveName)\n        defaults.synchronize()\n    }\n\n    static func restore(saveName: String) -> Any? {\n        return defaults.object(forKey: saveName)\n    }\n}\n/*:\n### 用法\n*/\nvar gameState = GameState(chapter: \"Black Mesa Inbound\", weapon: \"Crowbar\")\n\ngameState.chapter = \"Anomalous Materials\"\ngameState.weapon = \"Glock 17\"\nCheckPoint.save(gameState, saveName: \"gameState1\")\n\ngameState.chapter = \"Unforeseen Consequences\"\ngameState.weapon = \"MP5\"\nCheckPoint.save(gameState, saveName: \"gameState2\")\n\ngameState.chapter = \"Office Complex\"\ngameState.weapon = \"Crossbow\"\nCheckPoint.save(gameState, saveName: \"gameState3\")\n\nif let memento = CheckPoint.restore(saveName: \"gameState1\") as? Memento {\n    let finalState = GameState(memento: memento)\n    dump(finalState)\n}\n"
  },
  {
    "path": "source-cn/behavioral/observer.swift",
    "content": "/*:\n👓 观察者（Observer）\n---------------\n\n一个目标对象管理所有相依于它的观察者对象，并且在它本身的状态改变时主动发出通知\n\n### 示例：\n*/\nprotocol PropertyObserver : class {\n    func willChange(propertyName: String, newPropertyValue: Any?)\n    func didChange(propertyName: String, oldPropertyValue: Any?)\n}\n\nfinal class TestChambers {\n\n    weak var observer:PropertyObserver?\n\n    private let testChamberNumberName = \"testChamberNumber\"\n\n    var testChamberNumber: Int = 0 {\n        willSet(newValue) {\n            observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)\n        }\n        didSet {\n            observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)\n        }\n    }\n}\n\nfinal class Observer : PropertyObserver {\n    func willChange(propertyName: String, newPropertyValue: Any?) {\n        if newPropertyValue as? Int == 1 {\n            print(\"Okay. Look. We both said a lot of things that you're going to regret.\")\n        }\n    }\n\n    func didChange(propertyName: String, oldPropertyValue: Any?) {\n        if oldPropertyValue as? Int == 0 {\n            print(\"Sorry about the mess. I've really let the place go since you killed me.\")\n        }\n    }\n}\n/*:\n### 用法\n*/\nvar observerInstance = Observer()\nvar testChambers = TestChambers()\ntestChambers.observer = observerInstance\ntestChambers.testChamberNumber += 1\n"
  },
  {
    "path": "source-cn/behavioral/state.swift",
    "content": "/*:\n🐉 状态（State）\n---------\n\n在状态模式中，对象的行为是基于它的内部状态而改变的。\n这个模式允许某个类对象在运行时发生改变。\n\n### 示例：\n*/\nfinal class Context {\n\tprivate var state: State = UnauthorizedState()\n\n    var isAuthorized: Bool {\n        get { return state.isAuthorized(context: self) }\n    }\n\n    var userId: String? {\n        get { return state.userId(context: self) }\n    }\n\n\tfunc changeStateToAuthorized(userId: String) {\n\t\tstate = AuthorizedState(userId: userId)\n\t}\n\n\tfunc changeStateToUnauthorized() {\n\t\tstate = UnauthorizedState()\n\t}\n}\n\nprotocol State {\n\tfunc isAuthorized(context: Context) -> Bool\n\tfunc userId(context: Context) -> String?\n}\n\nclass UnauthorizedState: State {\n\tfunc isAuthorized(context: Context) -> Bool { return false }\n\n\tfunc userId(context: Context) -> String? { return nil }\n}\n\nclass AuthorizedState: State {\n\tlet userId: String\n\n\tinit(userId: String) { self.userId = userId }\n\n\tfunc isAuthorized(context: Context) -> Bool { return true }\n\n\tfunc userId(context: Context) -> String? { return userId }\n}\n/*:\n### 用法\n*/\nlet userContext = Context()\n(userContext.isAuthorized, userContext.userId)\nuserContext.changeStateToAuthorized(userId: \"admin\")\n(userContext.isAuthorized, userContext.userId) // now logged in as \"admin\"\nuserContext.changeStateToUnauthorized()\n(userContext.isAuthorized, userContext.userId)\n"
  },
  {
    "path": "source-cn/behavioral/strategy.swift",
    "content": "/*:\n💡 策略（Strategy）\n--------------\n\n对象有某个行为，但是在不同的场景中，该行为有不同的实现算法。策略模式：\n* 定义了一族算法（业务规则）；\n* 封装了每个算法；\n* 这族的算法可互换代替（interchangeable）。\n\n### 示例：\n*/\n\nstruct TestSubject {\n    let pupilDiameter: Double\n    let blushResponse: Double\n    let isOrganic: Bool\n}\n\nprotocol RealnessTesting: AnyObject {\n    func testRealness(_ testSubject: TestSubject) -> Bool\n}\n\nfinal class VoightKampffTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.pupilDiameter < 30.0 || testSubject.blushResponse == 0.0\n    }\n}\n\nfinal class GeneticTest: RealnessTesting {\n    func testRealness(_ testSubject: TestSubject) -> Bool {\n        return testSubject.isOrganic\n    }\n}\n\nfinal class BladeRunner {\n    private let strategy: RealnessTesting\n\n    init(test: RealnessTesting) {\n        self.strategy = test\n    }\n\n    func testIfAndroid(_ testSubject: TestSubject) -> Bool {\n        return !strategy.testRealness(testSubject)\n    }\n}\n\n/*:\n ### 用法\n */\n\nlet rachel = TestSubject(pupilDiameter: 30.2,\n                         blushResponse: 0.3,\n                         isOrganic: false)\n\n// Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n// Gaff is using a very precise method\nlet gaff = BladeRunner(test: GeneticTest())\nlet isDeckardAndroid = gaff.testIfAndroid(rachel)\n"
  },
  {
    "path": "source-cn/behavioral/template_method.swift",
    "content": "/*:\n📝 模板方法模式\n-----------\n\n 模板方法模式是一种行为设计模式， 它通过父类/协议中定义了一个算法的框架， 允许子类/具体实现对象在不修改结构的情况下重写算法的特定步骤。\n\n### 示例：\n*/\nprotocol Garden {\n    func prepareSoil()\n    func plantSeeds()\n    func waterPlants()\n    func prepareGarden()\n}\n\nextension Garden {\n\n    func prepareGarden() {\n        prepareSoil()\n        plantSeeds()\n        waterPlants()\n    }\n}\n\nfinal class RoseGarden: Garden {\n\n    func prepare() {\n        prepareGarden()\n    }\n\n    func prepareSoil() {\n        print (\"prepare soil for rose garden\")\n    }\n\n    func plantSeeds() {\n        print (\"plant seeds for rose garden\")\n    }\n\n    func waterPlants() {\n       print (\"water the rose garden\")\n    }\n}\n\n/*:\n### 用法\n*/\n\nlet roseGarden = RoseGarden()\nroseGarden.prepare()\n"
  },
  {
    "path": "source-cn/behavioral/visitor.swift",
    "content": "/*:\n🏃 访问者（Visitor）\n--------------\n\n封装某些作用于某种数据结构中各元素的操作，它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。\n\n### 示例：\n*/\nprotocol PlanetVisitor {\n\tfunc visit(planet: PlanetAlderaan)\n\tfunc visit(planet: PlanetCoruscant)\n\tfunc visit(planet: PlanetTatooine)\n    func visit(planet: MoonJedha)\n}\n\nprotocol Planet {\n\tfunc accept(visitor: PlanetVisitor)\n}\n\nfinal class MoonJedha: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetAlderaan: Planet {\n    func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetCoruscant: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class PlanetTatooine: Planet {\n\tfunc accept(visitor: PlanetVisitor) { visitor.visit(planet: self) }\n}\n\nfinal class NameVisitor: PlanetVisitor {\n\tvar name = \"\"\n\n\tfunc visit(planet: PlanetAlderaan)  { name = \"Alderaan\" }\n\tfunc visit(planet: PlanetCoruscant) { name = \"Coruscant\" }\n\tfunc visit(planet: PlanetTatooine)  { name = \"Tatooine\" }\n    func visit(planet: MoonJedha)     \t{ name = \"Jedha\" }\n}\n\n/*:\n### 用法\n*/\nlet planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedha()]\n\nlet names = planets.map { (planet: Planet) -> String in\n\tlet visitor = NameVisitor()\n    planet.accept(visitor: visitor)\n\n    return visitor.name\n}\n\nnames\n"
  },
  {
    "path": "source-cn/contents.md",
    "content": "\n## 目录\n\n* [行为型模式](Behavioral)\n* [创建型模式](Creational)\n* [结构型模式](Structural)"
  },
  {
    "path": "source-cn/contentsReadme.md",
    "content": "\n## 目录\n\n| [行为型模式](#行为型模式)                                    | [创建型模式](#创建型模式)                                 | [结构型模式](#结构型模式structural)                          |\n| ------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------------------ |\n| [🐝 责任链 Chain Of Responsibility](#-责任链chain-of-responsibility) | [🌰 抽象工厂 Abstract Factory](#-抽象工厂abstract-factory) | [🔌 适配器 Adapter](#-适配器adapter)                          |\n| [👫 命令 Command](#-命令command)                              | [👷 生成器 Builder](#-生成器builder)                       | [🌉 桥接 Bridge](#-桥接bridge)                                |\n| [🎶 解释器 Interpreter](#-解释器interpreter)                  | [🏭 工厂方法 Factory Method](#-工厂方法factory-method)     | [🌿 组合 Composite](#-组合composite)                          |\n| [🍫 迭代器 Iterator](#-迭代器iterator)                        | [🔂 单态 Monostate](#-单态monostate)                       | [🍧 修饰 Decorator](#-修饰decorator)                          |\n| [💐 中介者 Mediator](#-中介者mediator)                        | [🃏 原型 Prototype](#-原型prototype)                       | [🎁 外观 Façade](#-外观facade)                                |\n| [💾 备忘录 Memento](#-备忘录memento)                          | [💍 单例 Singleton](#-单例singleton)                       | [🍃 享元 Flyweight](#-享元flyweight)                          |\n| [👓 观察者 Observer](#-观察者observer)                        |                                                           | [☔ 保护代理 Protection Proxy](#-保护代理模式protection-proxy) |\n| [🐉 状态 State](#-状态state)                                  |                                                           | [🍬 虚拟代理 Virtual Proxy](#-虚拟代理virtual-proxy)          |\n| [💡 策略 Strategy](#-策略strategy)                            |                                                           |                                                              |\n| [📝 模板方法 Templdate Method](#-template-method)             |                                                           |                                                              |\n| [🏃 访问者 Visitor](#-访问者visitor)                          |                                                           |                                                              |\n"
  },
  {
    "path": "source-cn/creational/abstract_factory.swift",
    "content": "/*:\n🌰 抽象工厂（Abstract Factory）\n-------------\n\n抽象工厂模式提供了一种方式，可以将一组具有同一主题的单独的工厂封装起来。在正常使用中，客户端程序需要创建抽象工厂的具体实现，然后使用抽象工厂作为接口来创建这一主题的具体对象。\n\n### 示例：\n\n协议\n*/\n\nprotocol BurgerDescribing {\n    var ingredients: [String] { get }\n}\n\nstruct CheeseBurger: BurgerDescribing {\n    let ingredients: [String]\n}\n\nprotocol BurgerMaking {\n    func make() -> BurgerDescribing\n}\n\n// 工厂方法实现\n\nfinal class BigKahunaBurger: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Lettuce\", \"Tomato\"])\n    }\n}\n\nfinal class JackInTheBox: BurgerMaking {\n    func make() -> BurgerDescribing {\n        return CheeseBurger(ingredients: [\"Cheese\", \"Burger\", \"Tomato\", \"Onions\"])\n    }\n}\n\n/*:\n抽象工厂\n*/\n\nenum BurgerFactoryType: BurgerMaking {\n\n    case bigKahuna\n    case jackInTheBox\n\n    func make() -> BurgerDescribing {\n        switch self {\n        case .bigKahuna:\n            return BigKahunaBurger().make()\n        case .jackInTheBox:\n            return JackInTheBox().make()\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet bigKahuna = BurgerFactoryType.bigKahuna.make()\nlet jackInTheBox = BurgerFactoryType.jackInTheBox.make()\n"
  },
  {
    "path": "source-cn/creational/builder.swift",
    "content": "/*:\n👷 生成器（Builder）\n--------------\n\n一种对象构建模式。它可以将复杂对象的建造过程抽象出来（抽象类别），使这个抽象过程的不同实现方法可以构造出不同表现（属性）的对象。\n\n### 示例：\n*/\nfinal class DeathStarBuilder {\n\n    var x: Double?\n    var y: Double?\n    var z: Double?\n\n    typealias BuilderClosure = (DeathStarBuilder) -> ()\n\n    init(buildClosure: BuilderClosure) {\n        buildClosure(self)\n    }\n}\n\nstruct DeathStar : CustomStringConvertible {\n\n    let x: Double\n    let y: Double\n    let z: Double\n\n    init?(builder: DeathStarBuilder) {\n\n        if let x = builder.x, let y = builder.y, let z = builder.z {\n            self.x = x\n            self.y = y\n            self.z = z\n        } else {\n            return nil\n        }\n    }\n\n    var description:String {\n        return \"Death Star at (x:\\(x) y:\\(y) z:\\(z))\"\n    }\n}\n/*:\n### 用法\n*/\nlet empire = DeathStarBuilder { builder in\n    builder.x = 0.1\n    builder.y = 0.2\n    builder.z = 0.3\n}\n\nlet deathStar = DeathStar(builder:empire)\n"
  },
  {
    "path": "source-cn/creational/factory.swift",
    "content": "/*:\n🏭 工厂方法（Factory Method）\n-----------------------\n\n定义一个创建对象的接口，但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。\n\n### 示例：\n*/\nprotocol CurrencyDescribing {\n    var symbol: String { get }\n    var code: String { get }\n}\n\nfinal class Euro: CurrencyDescribing {\n    var symbol: String {\n        return \"€\"\n    }\n    \n    var code: String {\n        return \"EUR\"\n    }\n}\n\nfinal class UnitedStatesDolar: CurrencyDescribing {\n    var symbol: String {\n        return \"$\"\n    }\n    \n    var code: String {\n        return \"USD\"\n    }\n}\n\nenum Country {\n    case unitedStates\n    case spain\n    case uk\n    case greece\n}\n\nenum CurrencyFactory {\n    static func currency(for country: Country) -> CurrencyDescribing? {\n\n        switch country {\n            case .spain, .greece:\n                return Euro()\n            case .unitedStates:\n                return UnitedStatesDolar()\n            default:\n                return nil\n        }\n        \n    }\n}\n/*:\n### 用法\n*/\nlet noCurrencyCode = \"No Currency Code Available\"\n\nCurrencyFactory.currency(for: .greece)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .spain)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .unitedStates)?.code ?? noCurrencyCode\nCurrencyFactory.currency(for: .uk)?.code ?? noCurrencyCode\n"
  },
  {
    "path": "source-cn/creational/header.md",
    "content": "\n 创建型模式\n ========\n \n > 创建型模式是处理对象创建的设计模式，试图根据实际情况使用合适的方式创建对象。基本的对象创建方式可能会导致设计上的问题，或增加设计的复杂度。创建型模式通过以某种方式控制对象的创建来解决问题。\n >\n >**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E5%89%B5%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n "
  },
  {
    "path": "source-cn/creational/monostate.swift",
    "content": "/*:\n 🔂 单态（Monostate）\n ------------\n\n  单态模式是实现单一共享的另一种方法。不同于单例模式，它通过完全不同的机制，在不限制构造方法的情况下实现单一共享特性。\n  因此，在这种情况下，单态会将状态保存为静态，而不是将整个实例保存为单例。\n [单例和单态 - Robert C. Martin](http://staff.cs.utu.fi/~jounsmed/doos_06/material/SingletonAndMonostate.pdf)\n\n### 示例:\n*/\nclass Settings {\n\n    enum Theme {\n        case `default`\n        case old\n        case new\n    }\n\n    private static var theme: Theme?\n\n    var currentTheme: Theme {\n        get { Settings.theme ?? .default }\n        set(newTheme) { Settings.theme = newTheme }\n    }\n}\n/*:\n### 用法:\n*/\nimport SwiftUI\n\n// 改变主题\nlet settings = Settings() // 开始使用主题 .old\nsettings.currentTheme = .new // 改变主题为 .new\n\n// 界面一\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n// 界面二\nlet screenTitle: String = Settings().currentTheme == .old ? \"Itunes Connect\" : \"App Store Connect\"\n"
  },
  {
    "path": "source-cn/creational/prototype.swift",
    "content": "/*:\n🃏 原型（Prototype）\n--------------\n\n通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”，这个原型是可定制的。\n\n### 示例：\n*/\nclass MoonWorker {\n\n    let name: String\n    var health: Int = 100\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func clone() -> MoonWorker {\n        return MoonWorker(name: name)\n    }\n}\n/*:\n### 用法\n*/\nlet prototype = MoonWorker(name: \"Sam Bell\")\n\nvar bell1 = prototype.clone()\nbell1.health = 12\n\nvar bell2 = prototype.clone()\nbell2.health = 23\n\nvar bell3 = prototype.clone()\nbell3.health = 0\n"
  },
  {
    "path": "source-cn/creational/singleton.swift",
    "content": "/*:\n💍 单例（Singleton）\n--------------\n\n单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象，这样有利于我们协调系统整体的行为\n\n### 示例：\n*/\nfinal class ElonMusk {\n\n    static let shared = ElonMusk()\n\n    private init() {\n        // Private initialization to ensure just one instance is created.\n    }\n}\n/*:\n### 用法\n*/\nlet elon = ElonMusk.shared // There is only one Elon Musk folks.\n"
  },
  {
    "path": "source-cn/endComment",
    "content": "\n*/"
  },
  {
    "path": "source-cn/endSwiftCode",
    "content": "```\n\n"
  },
  {
    "path": "source-cn/footer.md",
    "content": "\nInfo\n====\n\n📖 Descriptions from: [Gang of Four Design Patterns Reference Sheet](http://www.blackwasp.co.uk/GangOfFour.aspx)\n"
  },
  {
    "path": "source-cn/imports.swift",
    "content": "\nimport Foundation\n"
  },
  {
    "path": "source-cn/startComment",
    "content": "/*:\n"
  },
  {
    "path": "source-cn/startSwiftCode",
    "content": "\n\n```swift"
  },
  {
    "path": "source-cn/structural/adapter.swift",
    "content": "/*:\n🔌 适配器（Adapter）\n--------------\n\n适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起，做法是将类自己的接口包裹在一个已存在的类中。\n\n### 示例：\n*/\nprotocol NewDeathStarSuperLaserAiming {\n    var angleV: Double { get }\n    var angleH: Double { get }\n}\n/*:\n**被适配者**\n*/\nstruct OldDeathStarSuperlaserTarget {\n    let angleHorizontal: Float\n    let angleVertical: Float\n\n    init(angleHorizontal: Float, angleVertical: Float) {\n        self.angleHorizontal = angleHorizontal\n        self.angleVertical = angleVertical\n    }\n}\n/*:\n**适配器**\n*/\nstruct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {\n\n    private let target: OldDeathStarSuperlaserTarget\n\n    var angleV: Double {\n        return Double(target.angleVertical)\n    }\n\n    var angleH: Double {\n        return Double(target.angleHorizontal)\n    }\n\n    init(_ target: OldDeathStarSuperlaserTarget) {\n        self.target = target\n    }\n}\n/*:\n### 用法\n*/\nlet target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)\nlet newFormat = NewDeathStarSuperlaserTarget(target)\n\nnewFormat.angleH\nnewFormat.angleV\n"
  },
  {
    "path": "source-cn/structural/bridge.swift",
    "content": "/*:\n🌉 桥接（Bridge）\n-----------\n\n桥接模式将抽象部分与实现部分分离，使它们都可以独立的变化。\n\n### 示例：\n*/\nprotocol Switch {\n    var appliance: Appliance { get set }\n    func turnOn()\n}\n\nprotocol Appliance {\n    func run()\n}\n\nfinal class RemoteControl: Switch {\n    var appliance: Appliance\n\n    func turnOn() {\n        self.appliance.run()\n    }\n    \n    init(appliance: Appliance) {\n        self.appliance = appliance\n    }\n}\n\nfinal class TV: Appliance {\n    func run() {\n        print(\"tv turned on\");\n    }\n}\n\nfinal class VacuumCleaner: Appliance {\n    func run() {\n        print(\"vacuum cleaner turned on\")\n    }\n}\n/*:\n### 用法\n*/\nlet tvRemoteControl = RemoteControl(appliance: TV())\ntvRemoteControl.turnOn()\n\nlet fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())\nfancyVacuumCleanerRemoteControl.turnOn()\n"
  },
  {
    "path": "source-cn/structural/composite.swift",
    "content": "/*:\n🌿 组合（Composite）\n--------------\n\n将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。\n\n### 示例：\n\n组件（Component）\n*/\nprotocol Shape {\n    func draw(fillColor: String)\n}\n/*:\n叶子节点（Leafs）\n*/\nfinal class Square: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a Square with color \\(fillColor)\")\n    }\n}\n\nfinal class Circle: Shape {\n    func draw(fillColor: String) {\n        print(\"Drawing a circle with color \\(fillColor)\")\n    }\n}\n\n/*:\n组合\n*/\nfinal class Whiteboard: Shape {\n\n    private lazy var shapes = [Shape]()\n\n    init(_ shapes: Shape...) {\n        self.shapes = shapes\n    }\n\n    func draw(fillColor: String) {\n        for shape in self.shapes {\n            shape.draw(fillColor: fillColor)\n        }\n    }\n}\n/*:\n### 用法\n*/\nvar whiteboard = Whiteboard(Circle(), Square())\nwhiteboard.draw(fillColor: \"Red\")\n"
  },
  {
    "path": "source-cn/structural/decorator.swift",
    "content": "/*:\n🍧 修饰（Decorator）\n--------------\n\n修饰模式，是面向对象编程领域中，一种动态地往一个类中添加新的行为的设计模式。\n就功能而言，修饰模式相比生成子类更为灵活，这样可以给某个对象而不是整个类添加一些功能。\n\n### 示例：\n*/\nprotocol CostHaving {\n    var cost: Double { get }\n}\n\nprotocol IngredientsHaving {\n    var ingredients: [String] { get }\n}\n\ntypealias BeverageDataHaving = CostHaving & IngredientsHaving\n\nstruct SimpleCoffee: BeverageDataHaving {\n    let cost: Double = 1.0\n    let ingredients = [\"Water\", \"Coffee\"]\n}\n\nprotocol BeverageHaving: BeverageDataHaving {\n    var beverage: BeverageDataHaving { get }\n}\n\nstruct Milk: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Milk\"]\n    }\n}\n\nstruct WhipCoffee: BeverageHaving {\n\n    let beverage: BeverageDataHaving\n\n    var cost: Double {\n        return beverage.cost + 0.5\n    }\n\n    var ingredients: [String] {\n        return beverage.ingredients + [\"Whip\"]\n    }\n}\n/*:\n### 用法\n*/\nvar someCoffee: BeverageDataHaving = SimpleCoffee()\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = Milk(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\nsomeCoffee = WhipCoffee(beverage: someCoffee)\nprint(\"Cost: \\(someCoffee.cost); Ingredients: \\(someCoffee.ingredients)\")\n"
  },
  {
    "path": "source-cn/structural/facade.swift",
    "content": "/*:\n🎁 外观（Facade）\n-----------\n\n外观模式为子系统中的一组接口提供一个统一的高层接口，使得子系统更容易使用。\n\n### 示例：\n*/\nfinal class Defaults {\n\n    private let defaults: UserDefaults\n\n    init(defaults: UserDefaults = .standard) {\n        self.defaults = defaults\n    }\n\n    subscript(key: String) -> String? {\n        get {\n            return defaults.string(forKey: key)\n        }\n\n        set {\n            defaults.set(newValue, forKey: key)\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet storage = Defaults()\n\n// Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n// Read\nstorage[\"Bishop\"]\n"
  },
  {
    "path": "source-cn/structural/flyweight.swift",
    "content": "/*:\n🍃 享元（Flyweight）\n--------------\n\n使用共享物件，用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件；它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。\n\n### 示例：\n*/\n// 特指咖啡生成的对象会是享元\nstruct SpecialityCoffee {\n    let origin: String\n}\n\nprotocol CoffeeSearching {\n    func search(origin: String) -> SpecialityCoffee?\n}\n\n// 菜单充当特制咖啡享元对象的工厂和缓存\nfinal class Menu: CoffeeSearching {\n\n    private var coffeeAvailable: [String: SpecialityCoffee] = [:]\n\n    func search(origin: String) -> SpecialityCoffee? {\n        if coffeeAvailable.index(forKey: origin) == nil {\n            coffeeAvailable[origin] = SpecialityCoffee(origin: origin)\n        }\n\n        return coffeeAvailable[origin]\n    }\n}\n\nfinal class CoffeeShop {\n    private var orders: [Int: SpecialityCoffee] = [:]\n    private let menu: CoffeeSearching\n\n    init(menu: CoffeeSearching) {\n        self.menu = menu\n    }\n\n    func takeOrder(origin: String, table: Int) {\n        orders[table] = menu.search(origin: origin)\n    }\n\n    func serve() {\n        for (table, origin) in orders {\n            print(\"Serving \\(origin) to table \\(table)\")\n        }\n    }\n}\n/*:\n### 用法\n*/\nlet coffeeShop = CoffeeShop(menu: Menu())\n\ncoffeeShop.takeOrder(origin: \"Yirgacheffe, Ethiopia\", table: 1)\ncoffeeShop.takeOrder(origin: \"Buziraguhindwa, Burundi\", table: 3)\n\ncoffeeShop.serve()\n"
  },
  {
    "path": "source-cn/structural/header.md",
    "content": "\n结构型模式（Structural）\n====================\n\n> 在软件工程中结构型模式是设计模式，借由一以贯之的方式来了解元件间的关系，以简化设计。\n>\n>**来源：** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)\n"
  },
  {
    "path": "source-cn/structural/protection_proxy.swift",
    "content": "/*:\n☔ 保护代理模式（Protection Proxy）\n------------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n保护代理用于限制访问。\n\n### 示例：\n*/\nprotocol DoorOpening {\n    func open(doors: String) -> String\n}\n\nfinal class HAL9000: DoorOpening {\n    func open(doors: String) -> String {\n        return (\"HAL9000: Affirmative, Dave. I read you. Opened \\(doors).\")\n    }\n}\n\nfinal class CurrentComputer: DoorOpening {\n    private var computer: HAL9000!\n\n    func authenticate(password: String) -> Bool {\n\n        guard password == \"pass\" else {\n            return false\n        }\n\n        computer = HAL9000()\n\n        return true\n    }\n\n    func open(doors: String) -> String {\n\n        guard computer != nil else {\n            return \"Access Denied. I'm afraid I can't do that.\"\n        }\n\n        return computer.open(doors: doors)\n    }\n}\n/*:\n### 用法\n*/\nlet computer = CurrentComputer()\nlet podBay = \"Pod Bay Doors\"\n\ncomputer.open(doors: podBay)\n\ncomputer.authenticate(password: \"pass\")\ncomputer.open(doors: podBay)\n"
  },
  {
    "path": "source-cn/structural/virtual_proxy.swift",
    "content": "/*:\n🍬 虚拟代理（Virtual Proxy）\n----------------\n\n在代理模式中，创建一个类代表另一个底层类的功能。\n虚拟代理用于对象的需时加载。\n\n### 示例：\n*/\nprotocol HEVSuitMedicalAid {\n    func administerMorphine() -> String\n}\n\nfinal class HEVSuit: HEVSuitMedicalAid {\n    func administerMorphine() -> String {\n        return \"Morphine administered.\"\n    }\n}\n\nfinal class HEVSuitHumanInterface: HEVSuitMedicalAid {\n\n    lazy private var physicalSuit: HEVSuit = HEVSuit()\n\n    func administerMorphine() -> String {\n        return physicalSuit.administerMorphine()\n    }\n}\n/*:\n### 用法\n*/\nlet humanInterface = HEVSuitHumanInterface()\nhumanInterface.administerMorphine()\n"
  }
]