Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Design Patterns implemented in Swift 5.0

A short cheat-sheet with Xcode 10.2 Playground (Design-Patterns.playground.zip).

πŸ‘· Project started by: @nsmeme (Oktawian Chojnacki)

πŸ‘· δΈ­ζ–‡η‰ˆη”± @binglogo (棒棒彬) 整理翻译。

πŸš€ How to generate README, Playground and zip from source: GENERATE.md

print("Welcome!")

Table of Contents

BehavioralCreationalStructural
🐝 Chain Of Responsibility🌰 Abstract FactoryπŸ”Œ Adapter
πŸ‘« CommandπŸ‘· BuilderπŸŒ‰ Bridge
🎢 Interpreter🏭 Factory Method🌿 Composite
🍫 IteratorπŸ”‚ Monostate🍧 Decorator
πŸ’ MediatorπŸƒ Prototype🎁 FaΓ§ade
πŸ’Ύ MementoπŸ’ SingletonπŸƒ Flyweight
πŸ‘“ Observerβ˜” Protection Proxy
πŸ‰ State🍬 Virtual Proxy
πŸ’‘ Strategy
πŸƒ Visitor

Behavioral

In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Source:wikipedia.org

🐝 Chain Of Responsibility

The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.

Example:

protocolWithdrawing{func withdraw(amount:Int)->Bool}finalclassMoneyPile:Withdrawing{letvalue:Intvarquantity:Intvarnext:Withdrawing?init(value:Int, quantity:Int, next:Withdrawing?){self.value = value
self.quantity = quantity
self.next = next
}func withdraw(amount:Int)->Bool{varamount= amount
func canTakeSomeBill(want:Int)->Bool{return(want /self.value)>0}varquantity=self.quantity
whilecanTakeSomeBill(want: amount){if quantity ==0{break}
amount -=self.value
quantity -=1}guard amount >0else{returntrue}iflet next =self.next {return next.withdraw(amount: amount)}returnfalse}}finalclassATM:Withdrawing{privatevarhundred:Withdrawingprivatevarfifty:Withdrawingprivatevartwenty:Withdrawingprivatevarten:WithdrawingprivatevarstartPile:Withdrawing{returnself.hundred
}init(hundred:Withdrawing,
fifty:Withdrawing,
twenty:Withdrawing,
ten:Withdrawing){self.hundred = hundred
self.fifty = fifty
self.twenty = twenty
self.ten = ten
}func withdraw(amount:Int)->Bool{return startPile.withdraw(amount: amount)}}

Usage

// Create piles of money and link them together 10 < 20 < 50 < 100.**
letten=MoneyPile(value:10, quantity:6, next:nil)lettwenty=MoneyPile(value:20, quantity:2, next: ten)letfifty=MoneyPile(value:50, quantity:2, next: twenty)lethundred=MoneyPile(value:100, quantity:1, next: fifty)
// Build ATM.
varatm=ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten)
atm.withdraw(amount:310) // Cannot because ATM has only 300
atm.withdraw(amount:100) // Can withdraw - 1x100

πŸ‘« Command

The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Example:

protocolDoorCommand{func execute()->String}finalclassOpenCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Opened \(doors)"}}finalclassCloseCommand:DoorCommand{letdoors:Stringrequiredinit(doors:String){self.doors = doors
}func execute()->String{return"Closed \(doors)"}}finalclassHAL9000DoorsOperations{letopenCommand:DoorCommandletcloseCommand:DoorCommandinit(doors:String){self.openCommand =OpenCommand(doors:doors)self.closeCommand =CloseCommand(doors:doors)}func close()->String{return closeCommand.execute()}func open()->String{return openCommand.execute()}}

Usage:

letpodBayDoors="Pod Bay Doors"letdoorModule=HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()

🎢 Interpreter

The interpreter pattern is used to evaluate sentences in a language.

Example

protocolIntegerExpression{func evaluate(_ context:IntegerContext)->Intfunc replace(character:Character, integerExpression:IntegerExpression)->IntegerExpressionfunc copied()->IntegerExpression}finalclassIntegerContext{privatevardata:[Character:Int]=[:]func lookup(name:Character)->Int{returnself.data[name]!
}func assign(expression:IntegerVariableExpression, value:Int){self.data[expression.name]= value
}}finalclassIntegerVariableExpression:IntegerExpression{letname:Characterinit(name:Character){self.name = name
}func evaluate(_ context:IntegerContext)->Int{return context.lookup(name:self.name)}func replace(character name:Character, integerExpression:IntegerExpression)->IntegerExpression{if name ==self.name {return integerExpression.copied()}else{returnIntegerVariableExpression(name:self.name)}}func copied()->IntegerExpression{returnIntegerVariableExpression(name:self.name)}}finalclassAddExpression:IntegerExpression{privatevaroperand1:IntegerExpressionprivatevaroperand2:IntegerExpressioninit(op1:IntegerExpression, op2:IntegerExpression){self.operand1 = op1
self.operand2 = op2
}func evaluate(_ context:IntegerContext)->Int{returnself.operand1.evaluate(context)+self.operand2.evaluate(context)}func replace(character:Character, integerExpression:IntegerExpression)->IntegerExpression{returnAddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))}func copied()->IntegerExpression{returnAddExpression(op1:self.operand1, op2:self.operand2)}}

Usage

varcontext=IntegerContext()vara=IntegerVariableExpression(name:"A")varb=IntegerVariableExpression(name:"B")varc=IntegerVariableExpression(name:"C")varexpression=AddExpression(op1: a, op2:AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value:2)
context.assign(expression: b, value:1)
context.assign(expression: c, value:3)varresult= expression.evaluate(context)

🍫 Iterator

The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Example:

structNovella{letname:String}structNovellas{letnovellas:[Novella]}structNovellasIterator:IteratorProtocol{privatevarcurrent=0privateletnovellas:[Novella]init(novellas:[Novella]){self.novellas = novellas
}mutatingfunc next()->Novella?{defer{ current +=1}return novellas.count > current ?novellas[current]:nil}}extensionNovellas:Sequence{func makeIterator()->NovellasIterator{returnNovellasIterator(novellas: novellas)}}

Usage

letgreatNovellas=Novellas(novellas:[Novella(name:"The Mist")])fornovellain greatNovellas {print("I've read: \(novella)")}

πŸ’ Mediator

The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.

Example

protocolReceiver{associatedtypeMessageTypefunc receive(message:MessageType)}protocolSender{associatedtypeMessageTypeassociatedtypeReceiverType:Receivervarrecipients:[ReceiverType]{get}func send(message:MessageType)}structProgrammer:Receiver{letname:Stringinit(name:String){self.name = name
}func receive(message:String){print("\(name) received: \(message)")}}finalclassMessageMediator:Sender{internalvarrecipients:[Programmer]=[]func add(recipient:Programmer){
recipients.append(recipient)}func send(message:String){forrecipientin recipients {
recipient.receive(message: message)}}}

Usage

func spamMonster(message:String, worker:MessageMediator){
worker.send(message: message)}letmessagesMediator=MessageMediator()letuser0=Programmer(name:"Linus Torvalds")letuser1=Programmer(name:"Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)spamMonster(message:"I'd Like to Add you to My Professional Network", worker: messagesMediator)

πŸ’Ύ Memento

The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Example

typealiasMemento=[String:String]

Originator

protocolMementoConvertible{varmemento:Memento{get}init?(memento:Memento)}structGameState:MementoConvertible{privateenumKeys{staticletchapter="com.valve.halflife.chapter"staticletweapon="com.valve.halflife.weapon"}varchapter:Stringvarweapon:Stringinit(chapter:String, weapon:String){self.chapter = chapter
self.weapon = weapon
}init?(memento:Memento){guardlet mementoChapter =memento[Keys.chapter],let mementoWeapon =memento[Keys.weapon]else{returnnil}
chapter = mementoChapter
weapon = mementoWeapon
}varmemento:Memento{return[Keys.chapter: chapter,Keys.weapon: weapon ]}}

Caretaker

enumCheckPoint{privatestaticletdefaults=UserDefaults.standard
staticfunc save(_ state:MementoConvertible, saveName:String){
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()}staticfunc restore(saveName:String)->Any?{return defaults.object(forKey: saveName)}}

Usage

vargameState=GameState(chapter:"Black Mesa Inbound", weapon:"Crowbar")
gameState.chapter ="Anomalous Materials"
gameState.weapon ="Glock 17"CheckPoint.save(gameState, saveName:"gameState1")
gameState.chapter ="Unforeseen Consequences"
gameState.weapon ="MP5"CheckPoint.save(gameState, saveName:"gameState2")
gameState.chapter ="Office Complex"
gameState.weapon ="Crossbow"CheckPoint.save(gameState, saveName:"gameState3")iflet memento =CheckPoint.restore(saveName:"gameState1")as?Memento{letfinalState=GameState(memento: memento)dump(finalState)}

πŸ‘“ Observer

The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

Example

protocolPropertyObserver:class{func willChange(propertyName:String, newPropertyValue:Any?)func didChange(propertyName:String, oldPropertyValue:Any?)}finalclassTestChambers{
weak varobserver:PropertyObserver?privatelettestChamberNumberName="testChamberNumber"vartestChamberNumber:Int=0{
willSet(newValue){
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)}}}finalclassObserver:PropertyObserver{func willChange(propertyName:String, newPropertyValue:Any?){if newPropertyValue as?Int==1{print("Okay. Look. We both said a lot of things that you're going to regret.")}}func didChange(propertyName:String, oldPropertyValue:Any?){if oldPropertyValue as?Int==0{print("Sorry about the mess. I've really let the place go since you killed me.")}}}

Usage

varobserverInstance=Observer()vartestChambers=TestChambers()
testChambers.observer = observerInstance
testChambers.testChamberNumber +=1

πŸ‰ State

The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Example

finalclassContext{privatevarstate:State=UnauthorizedState()varisAuthorized:Bool{get{return state.isAuthorized(context:self)}}varuserId:String?{get{return state.userId(context:self)}}func changeStateToAuthorized(userId:String){
state =AuthorizedState(userId: userId)}func changeStateToUnauthorized(){
state =UnauthorizedState()}}protocolState{func isAuthorized(context:Context)->Boolfunc userId(context:Context)->String?}classUnauthorizedState:State{func isAuthorized(context:Context)->Bool{returnfalse}func userId(context:Context)->String?{returnnil}}classAuthorizedState:State{letuserId:Stringinit(userId:String){self.userId = userId }func isAuthorized(context:Context)->Bool{returntrue}func userId(context:Context)->String?{return userId }}

Usage

letuserContext=Context()(userContext.isAuthorized, userContext.userId)
userContext.changeStateToAuthorized(userId:"admin")(userContext.isAuthorized, userContext.userId) // now logged in as "admin"
userContext.changeStateToUnauthorized()(userContext.isAuthorized, userContext.userId)

πŸ’‘ Strategy

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Example

structTestSubject{letpupilDiameter:DoubleletblushResponse:DoubleletisOrganic:Bool}protocolRealnessTesting:AnyObject{func testRealness(_ testSubject:TestSubject)->Bool}finalclassVoightKampffTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.pupilDiameter <30.0 || testSubject.blushResponse ==0.0}}finalclassGeneticTest:RealnessTesting{func testRealness(_ testSubject:TestSubject)->Bool{return testSubject.isOrganic
}}finalclassBladeRunner{privateletstrategy:RealnessTestinginit(test:RealnessTesting){self.strategy = test
}func testIfAndroid(_ testSubject:TestSubject)->Bool{return !strategy.testRealness(testSubject)}}

Usage

letrachel=TestSubject(pupilDiameter:30.2,
blushResponse:0.3,
isOrganic:false)
// Deckard is using a traditional test
letdeckard=BladeRunner(test:VoightKampffTest())letisRachelAndroid= deckard.testIfAndroid(rachel)
// Gaff is using a very precise method
letgaff=BladeRunner(test:GeneticTest())letisDeckardAndroid= gaff.testIfAndroid(rachel)

πŸ“ Template Method

The template method pattern defines the steps of an algorithm and allows the redefinition of one or more of these steps. In this way, the template method protects the algorithm, the order of execution and provides abstract methods that can be implemented by concrete types.

Example

protocolGarden{func prepareSoil()func plantSeeds()func waterPlants()func prepareGarden()}extensionGarden{func prepareGarden(){prepareSoil()plantSeeds()waterPlants()}}finalclassRoseGarden:Garden{func prepare(){prepareGarden()}func prepareSoil(){print("prepare soil for rose garden")}func plantSeeds(){print("plant seeds for rose garden")}func waterPlants(){print("water the rose garden")}}

Usage

letroseGarden=RoseGarden()
roseGarden.prepare()

πŸƒ Visitor

The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.

Example

protocolPlanetVisitor{func visit(planet:PlanetAlderaan)func visit(planet:PlanetCoruscant)func visit(planet:PlanetTatooine)func visit(planet:MoonJedha)}protocolPlanet{func accept(visitor:PlanetVisitor)}finalclassMoonJedha:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetAlderaan:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetCoruscant:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassPlanetTatooine:Planet{func accept(visitor:PlanetVisitor){ visitor.visit(planet:self)}}finalclassNameVisitor:PlanetVisitor{varname=""func visit(planet:PlanetAlderaan){ name ="Alderaan"}func visit(planet:PlanetCoruscant){ name ="Coruscant"}func visit(planet:PlanetTatooine){ name ="Tatooine"}func visit(planet:MoonJedha){ name ="Jedha"}}

Usage

letplanets:[Planet]=[PlanetAlderaan(),PlanetCoruscant(),PlanetTatooine(),MoonJedha()]letnames= planets.map{(planet:Planet)->Stringinletvisitor=NameVisitor()
planet.accept(visitor: visitor)return visitor.name
}
names

Creational

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Source:wikipedia.org

🌰 Abstract Factory

The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Example

Protocols

protocolBurgerDescribing{varingredients:[String]{get}}structCheeseBurger:BurgerDescribing{letingredients:[String]}protocolBurgerMaking{func make()->BurgerDescribing}
// Number implementations with factory methods
finalclassBigKahunaBurger:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Lettuce","Tomato"])}}finalclassJackInTheBox:BurgerMaking{func make()->BurgerDescribing{returnCheeseBurger(ingredients:["Cheese","Burger","Tomato","Onions"])}}

Abstract factory

enumBurgerFactoryType:BurgerMaking{case bigKahuna
case jackInTheBox
func make()->BurgerDescribing{switchself{case.bigKahuna:returnBigKahunaBurger().make()case.jackInTheBox:returnJackInTheBox().make()}}}

Usage

letbigKahuna=BurgerFactoryType.bigKahuna.make()letjackInTheBox=BurgerFactoryType.jackInTheBox.make()

πŸ‘· Builder

The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Example

finalclassDeathStarBuilder{varx:Double?vary:Double?varz:Double?typealiasBuilderClosure=(DeathStarBuilder)->()init(buildClosure:BuilderClosure){buildClosure(self)}}structDeathStar:CustomStringConvertible{letx:Doublelety:Doubleletz:Doubleinit?(builder:DeathStarBuilder){iflet x = builder.x,let y = builder.y,let z = builder.z {self.x = x
self.y = y
self.z = z
}else{returnnil}}vardescription:String{return"Death Star at (x:\(x) y:\(y) z:\(z))"}}

Usage

letempire=DeathStarBuilder{ builder in
builder.x =0.1
builder.y =0.2
builder.z =0.3}letdeathStar=DeathStar(builder:empire)

🏭 Factory Method

The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Example

protocolCurrencyDescribing{varsymbol:String{get}varcode:String{get}}finalclassEuro:CurrencyDescribing{varsymbol:String{return"€"}varcode:String{return"EUR"}}finalclassUnitedStatesDolar:CurrencyDescribing{varsymbol:String{return"$"}varcode:String{return"USD"}}enumCountry{case unitedStates
case spain
case uk
case greece
}enumCurrencyFactory{staticfunc currency(for country:Country)->CurrencyDescribing?{switch country {case.spain,.greece:returnEuro()case.unitedStates:returnUnitedStatesDolar()default:returnnil}}}

Usage

letnoCurrencyCode="No Currency Code Available"CurrencyFactory.currency(for:.greece)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.spain)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.unitedStates)?.code ?? noCurrencyCode
CurrencyFactory.currency(for:.uk)?.code ?? noCurrencyCode

πŸ”‚ Monostate

The monostate pattern is another way to achieve singularity. It works through a completely different mechanism, it enforces the behavior of singularity without imposing structural constraints. So in that case, monostate saves the state as static instead of the entire instance as a singleton. SINGLETON and MONOSTATE - Robert C. Martin

Example:

struct Settings {enum Theme {
case .old
case .new
}privatestaticvartheme:ThemevarcurrentTheme:Theme{get{Settings.theme }set(newTheme){Settings.theme = newTheme }}}

Usage:

// When change the theme
letsettings=Settings() // Starts using theme .old
settings.currentTheme =.new // Change theme to .new
//On screen 1
letscreenColor:Color=Settings().currentTheme ==.old ?.gray :.white
//On screen 2
letscreenTitle:String=Settings().currentTheme ==.old ?"Itunes Connect":"App Store Connect"

πŸƒ Prototype

The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Example

structMoonWorker{letname:Stringvarhealth:Int=100init(name:String){self.name = name
}func clone()->MoonWorker{returnMoonWorker(name: name)}}

Usage

letprototype=MoonWorker(name:"Sam Bell")varbell1= prototype.clone()
bell1.health =12varbell2= prototype.clone()
bell2.health =23varbell3= prototype.clone()
bell3.health =0

πŸ’ Singleton

The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern!

Example:

finalclassElonMusk{staticletshared=ElonMusk()privateinit(){
// Private initialization to ensure just one instance is created.
}}

Usage:

letelon=ElonMusk.shared // There is only one Elon Musk folks.

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source:wikipedia.org

πŸ”Œ Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example

protocolNewDeathStarSuperLaserAiming{varangleV:Double{get}varangleH:Double{get}}

Adaptee

structOldDeathStarSuperlaserTarget{letangleHorizontal:FloatletangleVertical:Floatinit(angleHorizontal:Float, angleVertical:Float){self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}}

Adapter

structNewDeathStarSuperlaserTarget:NewDeathStarSuperLaserAiming{privatelettarget:OldDeathStarSuperlaserTargetvarangleV:Double{returnDouble(target.angleVertical)}varangleH:Double{returnDouble(target.angleHorizontal)}init(_ target:OldDeathStarSuperlaserTarget){self.target = target
}}

Usage

lettarget=OldDeathStarSuperlaserTarget(angleHorizontal:14.0, angleVertical:12.0)letnewFormat=NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV

πŸŒ‰ Bridge

The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Example

protocolSwitch{varappliance:Appliance{getset}func turnOn()}protocolAppliance{func run()}finalclassRemoteControl:Switch{varappliance:Appliancefunc turnOn(){self.appliance.run()}init(appliance:Appliance){self.appliance = appliance
}}finalclassTV:Appliance{func run(){print("tv turned on");
}}finalclassVacuumCleaner:Appliance{func run(){print("vacuum cleaner turned on")}}

Usage

lettvRemoteControl=RemoteControl(appliance:TV())
tvRemoteControl.turnOn()letfancyVacuumCleanerRemoteControl=RemoteControl(appliance:VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()

🌿 Composite

The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Example

Component

protocolShape{func draw(fillColor:String)}

Leafs

finalclassSquare:Shape{func draw(fillColor:String){print("Drawing a Square with color \(fillColor)")}}finalclassCircle:Shape{func draw(fillColor:String){print("Drawing a circle with color \(fillColor)")}}

Composite

finalclassWhiteboard:Shape{private lazy varshapes=[Shape]()init(_ shapes:Shape...){self.shapes = shapes
}func draw(fillColor:String){forshapeinself.shapes {
shape.draw(fillColor: fillColor)}}}

Usage:

varwhiteboard=Whiteboard(Circle(),Square())
whiteboard.draw(fillColor:"Red")

🍧 Decorator

The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Example

protocolCostHaving{varcost:Double{get}}protocolIngredientsHaving{varingredients:[String]{get}}typealiasBeverageDataHaving=CostHaving&IngredientsHavingstructSimpleCoffee:BeverageDataHaving{letcost:Double=1.0letingredients=["Water","Coffee"]}protocolBeverageHaving:BeverageDataHaving{varbeverage:BeverageDataHaving{get}}structMilk:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Milk"]}}structWhipCoffee:BeverageHaving{letbeverage:BeverageDataHavingvarcost:Double{return beverage.cost +0.5}varingredients:[String]{return beverage.ingredients +["Whip"]}}

Usage:

varsomeCoffee:BeverageDataHaving=SimpleCoffee()print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =Milk(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee =WhipCoffee(beverage: someCoffee)print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")

🎁 Façade

The facade pattern is used to define a simplified interface to a more complex subsystem.

Example

finalclassDefaults{privateletdefaults:UserDefaultsinit(defaults:UserDefaults=.standard){self.defaults = defaults
}
subscript(key:String)->String?{get{return defaults.string(forKey: key)}set{
defaults.set(newValue, forKey: key)}}}

Usage

letstorage=Defaults()
// Store
storage["Bishop"]="Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]

πŸƒ Flyweight

The flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

Example

// Instances of SpecialityCoffee will be the Flyweights
structSpecialityCoffee{letorigin:String}protocolCoffeeSearching{func search(origin:String)->SpecialityCoffee?}
// Menu acts as a factory and cache for SpecialityCoffee flyweight objects
finalclassMenu:CoffeeSearching{privatevarcoffeeAvailable:[String:SpecialityCoffee]=[:]func search(origin:String)->SpecialityCoffee?{if coffeeAvailable.index(forKey: origin)==nil{coffeeAvailable[origin]=SpecialityCoffee(origin: origin)}returncoffeeAvailable[origin]}}finalclassCoffeeShop{privatevarorders:[Int:SpecialityCoffee]=[:]privateletmenu:CoffeeSearchinginit(menu:CoffeeSearching){self.menu = menu
}func takeOrder(origin:String, table:Int){orders[table]= menu.search(origin: origin)}func serve(){for(table, origin)in orders {print("Serving \(origin) to table \(table)")}}}

Usage

letcoffeeShop=CoffeeShop(menu:Menu())
coffeeShop.takeOrder(origin:"Yirgacheffe, Ethiopia", table:1)
coffeeShop.takeOrder(origin:"Buziraguhindwa, Burundi", table:3)
coffeeShop.serve()

β˜” Protection Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Protection proxy is restricting access.

Example

protocolDoorOpening{func open(doors:String)->String}finalclassHAL9000:DoorOpening{func open(doors:String)->String{return("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")}}finalclassCurrentComputer:DoorOpening{privatevarcomputer:HAL9000!func authenticate(password:String)->Bool{guard password =="pass"else{returnfalse}
computer =HAL9000()returntrue}func open(doors:String)->String{guard computer !=nilelse{return"Access Denied. I'm afraid I can't do that."}return computer.open(doors: doors)}}

Usage

letcomputer=CurrentComputer()letpodBay="Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password:"pass")
computer.open(doors: podBay)

🍬 Virtual Proxy

The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. Virtual proxy is used for loading object on demand.

Example

protocolHEVSuitMedicalAid{func administerMorphine()->String}finalclassHEVSuit:HEVSuitMedicalAid{func administerMorphine()->String{return"Morphine administered."}}finalclassHEVSuitHumanInterface:HEVSuitMedicalAid{
lazy privatevarphysicalSuit:HEVSuit=HEVSuit()func administerMorphine()->String{return physicalSuit.administerMorphine()}}

Usage

lethumanInterface=HEVSuitHumanInterface()
humanInterface.administerMorphine()

Info

πŸ“– Descriptions from: Gang of Four Design Patterns Reference Sheet

About

πŸ“– Design Patterns implemented in Swift 5.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages