[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-6682":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":19,"rankGlobal":10,"rankLanguage":10,"license":20,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":21,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":32,"readmeContent":33,"aiSummary":34,"trendingCount":16,"starSnapshotCount":16,"syncStatus":35,"lastSyncTime":36,"discoverSource":37},6682,"Design-Patterns-In-Swift","ochococo\u002FDesign-Patterns-In-Swift","ochococo","📖 Design Patterns implemented in Swift 5.0","",null,"Swift",15254,1734,644,4,0,1,7,44.72,"GNU General Public License v3.0",false,"master",true,[25,26,27,28,29,30,31],"computer-science","design-patterns","gang-of-four","good-practices","playground","swift","swift-5","2026-06-12 02:01:28","\n\nDesign Patterns implemented in Swift 5.0\n========================================\n\nA short cheat-sheet with Xcode 10.2 Playground ([Design-Patterns.playground.zip](https:\u002F\u002Fraw.githubusercontent.com\u002Fochococo\u002FDesign-Patterns-In-Swift\u002Fmaster\u002FDesign-Patterns.playground.zip)).\n\n### [🇨🇳中文版](https:\u002F\u002Fgithub.com\u002Fochococo\u002FDesign-Patterns-In-Swift\u002Fblob\u002Fmaster\u002FREADME-CN.md)\n\n👷 Project started by: [@nsmeme](http:\u002F\u002Ftwitter.com\u002Fnsmeme) (Oktawian Chojnacki)\n\n👷 中文版由 [@binglogo](https:\u002F\u002Ftwitter.com\u002Fbinglogo) (棒棒彬) 整理翻译。\n\n🚀 How to generate README, Playground and zip from source: [CONTRIBUTING.md](https:\u002F\u002Fgithub.com\u002Fochococo\u002FDesign-Patterns-In-Swift\u002Fblob\u002Fmaster\u002FCONTRIBUTING.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:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FBehavioral_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 \u002F 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\u002F\u002F Create piles of money and link them together 10 \u003C 20 \u003C 50 \u003C 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\u002F\u002F Build ATM.\nvar atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)\natm.withdraw(amount: 310) \u002F\u002F Cannot because ATM has only 300\natm.withdraw(amount: 100) \u002F\u002F 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)) \u002F\u002F 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) \u002F\u002F 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 \u003C 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\u002F\u002F Deckard is using a traditional test\nlet deckard = BladeRunner(test: VoightKampffTest())\nlet isRachelAndroid = deckard.testIfAndroid(rachel)\n\n\u002F\u002F 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:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCreational_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\u002F\u002F 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:\u002F\u002Fstaff.cs.utu.fi\u002F~jounsmed\u002Fdoos_06\u002Fmaterial\u002FSingletonAndMonostate.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\u002F\u002F When change the theme\nlet settings = Settings() \u002F\u002F Starts using theme .old\nsettings.currentTheme = .new \u002F\u002F Change theme to .new\n\n\u002F\u002F On screen 1\nlet screenColor: Color = Settings().currentTheme == .old ? .gray : .white\n\n\u002F\u002F 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        \u002F\u002F Private initialization to ensure just one instance is created.\n    }\n}\n```\n\n### Usage:\n\n```swift\nlet elon = ElonMusk.shared \u002F\u002F 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:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FStructural_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\u002F\u002F Store\nstorage[\"Bishop\"] = \"Disconnect me. I’d rather be nothing\"\n\n\u002F\u002F 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\u002F\u002F 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\u002F\u002F 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:\u002F\u002Fwww.blackwasp.co.uk\u002FGangOfFour.aspx)\n","该项目是用Swift 5.0实现的设计模式集合。它包含了行为型、创建型和结构型三大类设计模式的具体代码示例，每种模式都有详细的解释与演示。项目提供了一个Xcode Playground文件，方便开发者直接运行和测试这些设计模式。适合希望学习或应用面向对象设计原则及模式的iOS或macOS开发者在实际编程中参考使用。",2,"2026-06-11 03:08:18","top_language"]