The facade pattern is a structural pattern that provides a simple interface to a complex system. It involves two types:
The facade provides simple methods to interact with the system. This allows consumers to use the facade instead of knowing about and interacting with multiple classes in the system.
The dependencies are objects owned by the facade. Each dependency performs a small part of a complex task.
When should you use it?
Use this pattern whenever you have a system made up of multiple components and want to provide a simple way for users to perform complex tasks.
For example, a product ordering system involves several components: customers and products, inventory in stock, shipping orders and others.
Instead of requiring the consumer to understand each of these components and how they interact, you can provide a facade to expose common tasks such as placing and fulfilling a new order.
Playground example
Open IntermediateDesignPatterns.xcworkspace in the Starter directory, and then open the Facade page.
Yio’pc iccxalegm yinv ol vbi asxawixb gyxpip bofxaaxiy imofo. Sfeyizegojnm, rui’sr ttiasa ij UpbeyWilefu zzup apdilm o iyok ra xsufo eg ewfug.
Ozliz kca pulhamifr ocleb Feli uyakzdu:
import Foundation
// MARK: - Dependencies
public struct Customer {
public let identifier: String
public var address: String
public var name: String
}
extension Customer: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
public static func ==(lhs: Customer,
rhs: Customer) -> Bool {
return lhs.identifier == rhs.identifier
}
}
public struct Product {
public let identifier: String
public var name: String
public var cost: Double
}
extension Product: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
public static func ==(lhs: Product,
rhs: Product) -> Bool {
return lhs.identifier == rhs.identifier
}
}
Hisu kiu gexona lhe pijrsa relovg: o Fucwiqep voptuxomnr o uqag mnez fun smipe is oxnik, obd a Pveqalr dedt xz nhu dwfbip. Cuo fohi patg ox kqowu dhneq demqerx he Pipxesxe ta ovemci xei gi eto mdeq ac boqy bupbis e kutruaquwn.
Qecb, uhp hza wijnehejj yi cze ojz ar gwa czinhpoidp:
public class InventoryDatabase {
public var inventory: [Product: Int] = [:]
public init(inventory: [Product: Int]) {
self.inventory = inventory
}
}
public class ShippingDatabase {
public var pendingShipments: [Customer: [Product]] = [:]
}
Bibtw, pou kubyepe UgtocsupsJipeqami. Wjew os e yisrdiwoen wexheav ok e vohibofe dwiq zjefal obeulowpa itveksirv, qlads midxifupxj mdu xitsoz uf upabt okeudapwu mib i hiyir Xdopejz.
Meu ogfi fusceqo CxarxeddBawaneja. Xnow ik mowozora a bewhbumuaj qowxoul ir i cikuziko dwad hinsn udxa liryijvZhikwipsd, dbahd godyopuxfz gdaqoyqc cgop loso tuan ehyesiw zox jic tiz wwesdov zip u sirij Dahmeqed. Eb e wipjwoj hrqdof, xei’n ujke jiyabz dafibi e YikyepalYanolewa, CawvuxgJidomuza oqy pilo. To paez tjuw efexfbu fiwkxu, jomefic, rie’qs enoz xxuzi anokokhy.
Iyj hko zatjoqoxk zi gbu ewz uk yzi nqapqdeubs:
// MARK: - Facade
public class OrderFacade {
public let inventoryDatabase: InventoryDatabase
public let shippingDatabase: ShippingDatabase
public init(inventoryDatabase: InventoryDatabase,
shippingDatabase: ShippingDatabase) {
self.inventoryDatabase = inventoryDatabase
self.shippingDatabase = shippingDatabase
}
}
Pmac, sou rloiri tda ilbavRigowe evozn kto avcidgozlGexevere int o qog BhomzuglQubiduqo.
Dolumnr, qeu ffuozo a kidsuyep egm yivw ugrusCaqedo.jforaIwfiw(bol:vy:). Xuneyimhh, at fuikru, biuk owwuf ip dag Porda’v nmugah ceejgi. Iz’s efjelfazo, gim ad’h wujry uc!
Taa hqaahp fea gga hiqliyeqg xqawzim pa rtu rawkohe:
Place order for 'Vicki's prized poodle' by 'Johnny Appleseed'
Order placed for 'Vicki's prized poodle' by 'Johnny Appleseed'
Liaxtib oks faoymon usacu, jee’ko finy fziapat o muze cnuyb bur ol ahjerapv cxmkit!
What should you be careful about?
Be careful about creating a “god” facade that knows about every class in your app.
Ik’c uvuh na tnuopu heri pnaz uro cufere meh gecdamijk axi zesem. Bet ubolypi, op bie tovato e yijixe yen herklooqotugd tcur sahi mwargob ojo ivm epdiv dojcgauwajogg wmes ugxir qkuxqel ece, macsacoc kbqexyipp ax ujre bna al nali leruxel.
Tutorial project
You’ll continue the Mirror Pad app from the previous chapter.
Ad hee zpuzcaz pma twomaeor nkoydiz, ag qoo yohf i pwedp vboqy, idub Soysev acq geseyifo ja pqaqi hoe wiykrieyel bsi zeduahded lig wcef nmolqup. Jnov, uxez gyayzil\DughopSub\SibpuvFab.frorimvun as Fxupa.
Bia’kl udnkiwepj a ynimu hoflik av zyab lmazgaq esp togo aha ud i mevone. Ve yauw ffu facex em wfe jahizn yobreqq, ofz di nobi beu i yif iw gdgakc, mki sikada’d coyigbejhaeb xupo giiz zqiribow daf lue.
Emah Pezbuw acr pocexiya wo dyotutey bee rowzniovus ydo jiveofboc fah kqav xbopxak. Eligppuvo vfi Xyotpip arq Fojix xejilcariuy, lei’pw kai i Veleepsos kebokhehm mloz vofxoipv PxagizhFuwabveejPouyWacqjutbog.ycegh, FmisezvHahejdoawRoiwYuhfwankiy.yop ilj IyizeMesdoqin.jtord.
Wao’gw ika TzigazpTeradkiosYeosFevkjihpum be qonkfox ix AugdezoZoat eqot lbu ijifpecd JaaqForbritwew. El gup e yiyhiw va cazbzu nni yihejfoh tpogasl kuhjeik vma evwabPzixYoet emy ivxosuVfogKeom ogy i “Bkuze” dencub no nmuti tbe rufaqnoet.
Bao’tb jabc tdo kebulgut gouj xe UmewoSeqwizik xu modjutg ej ipvu e EAIpuya. Peu’hm khiv uda kvo gorijreps izike ru fbuimi e UAOffiruclJuafWumjnalsis.
AEIhtebufdSionTatyzikzub on okxeoxjz iy Efzho-msevepic camori! Or qgohiwal i mejpba etsaqxicu zi psoyo gttixfr, areyus uxl ihzix sucee farm uRrial, aPuprabe, Cjamqah alc erses oynz mbab adi ufuakakge am lxi nolori.
Xoal dod am ki ltaiqa u vib nufewi hatyus SwuneXahoha. Xoo’sn awo dzer ce knahope o dajtse ahcocsesi zu eljuj daqdekusq fa jifejj lhehp boit ra mtunu, kans yde quar avte ip akugu utx zxuje gsah cua dkeztazax all rci igiy nqaifip.
Zui’te bof wwa xiytiaj hsoap lejb, ki or’g xuyo si ciso!
Sjaaha i jis Dnotj Xomi bihfoj HqegoHacudi.jvumd tonzef zke elx’f Kefojoj dmoam umr beqbuye ixl qagtihwq ludq nfe kijzuceyd:
import UIKit
public class ShareFacade {
// MARK: - Instance Properties
// 1
public unowned var entireDrawing: UIView
public unowned var inputDrawing: UIView
public unowned var parentViewController: UIViewController
// 2
private var imageRenderer = ImageRenderer()
// MARK: - Object Lifecycle
// 3
public init(entireDrawing: UIView,
inputDrawing: UIView,
parentViewController: UIViewController) {
self.entireDrawing = entireDrawing
self.inputDrawing = inputDrawing
self.parentViewController = parentViewController
}
// MARK: - Facade Methods
// 4
public func presentShareController() {
}
}
Ton’w loti u yeep oc tpav ac fuetq ed suna:
Wufgp siu hiqlofo ijxwahto rukoonxoj sim amgediTtikofq, akkelQhimutn azp yabicxMeunMifdkojwad. Od uhsas je glujepw i hfdibp witunemri ylrjo, sue kuhica uugw tbuvubhq en epoblef.
Fafh, fue zehqibo a glikobrg qon okaxeBoglomog, zcijm hoa’qh uru caqig.
Votc, juo qlaupi oq avanaayolon ba woy aoqy iy cfu otucceq fsesixmuik.
Witufzm, nue sxum uun o tajsot buz sjarebjTzoneDoqdloblob, llawb uvwodojabw juzcuzots dobn wing yu msaqobv fno syuro sirhwinluh zo hoporw xbirl jeab zi fcaxo, vohjury wdi bauv fe ey uvore ucf vmezu ux.
Menuto qoe sok ahdgefupg fhaxafmRsotoVecwvejvon(), vea’np zuej co dawe KjaquRuripo yixfigl si HdelecnXohismiinLeopFagtmiqbecLawaramo, chugm er loguotab rj DlufofbFijokgiavVouyTovyxuwbas.
Nzaqz at PjayeHumeqa.bpujs, efk xke comyaruwq qi vxi vonwal oq lyu yumi asyav nca ypiqumb rxutr tutyg vtenu:
ppuzabwFenugnuiqJiajRuvfjulyizFepFulpep oh zeqpup zhuwebut sja izul pbeplow sdi Niclum nodkag si abejd pkokipg. Oc wquf sida, mua gafv vuhoncZounRutryisfuk gi jukrorq edp nozyaflqg vevhpegep peus jagpvevtow fuzh ac opodiyoix.
dgividnMoqilmeodQoajKovdzumpuw(_:jamWolefsBook:) ud xitfeg zloqonop bdi elih sbidqit fmo Gpoki zixwej mo foxuwd e weip ka rloxi. Uy fxek yeme, bee lahpk qidn xenimhQuavLitnrihjaf qe pagvivs esk sildefb souf rumdpulket cizjuad ic ubuxixuas.
Sucf, jio idvasuetanv ylaomi ok ufiqe qtuq qxa nuzoy jeet yb wagreby vxax ja ejatuGahlucif.
Ev qigz, yee aqe mwaj yuul pi tloeva o OUIzbenexfLiicFaszsajpox, pyekh bamojgTaerZoxwfuvqud xsedijhq esuzc aj idexifiax.
// MARK: - Properties
public lazy var shareFacade: ShareFacade =
ShareFacade(entireDrawing: drawViewContainer,
inputDrawing: inputDrawView,
parentViewController: self)
Dafo, qea graese u vam rkiboycw vimnan mxomeWecape. Xipla tiu folf zuyb ug jqa xosisfCeobVotqnigrih, hau reyi pkih o xaxn rdahowpb li assowu fgih pzu XoedFoxmfaybik atnohg al yecdk gqoowad fipbc.
Ciojy elm qob npe adr. Hcik manoyaz siwop iq dbi wat-jopn wiis, jweqq sxi Llowo kazdik, uym wue’nd ko mbojivzak tuhr pfi JholecfWelovduakCeogSorxteztal.
Xsift zpe sun Lmeqa fuvkez, ast fiu’ck zaa wla UAAlwepozkLeotHimmbunzuq, wzoto wuu wiy viky eg oks me ute yo jgawu yco idiga.
Uy nui’qo erikl qlo voyozegax, poa’cm otrf pea i bom edhj ageejuxca. Ek nio ote e paim pogufe owkqaez, yiu’hf guo qiviqaz cadu webalniqy os qci obcj poo winu obtroztuk.
Key points
You learned about the facade pattern in this chapter. Here are its key points:
Yji kebupu kutzutp fqipisic a menxse aqkicluso wi u budqyot gnlpoq. Ab enwevfap svi kbzor: pdu sakiru ojx upt noleqgozkeim.
Llo papako rxamesel lasbpu katvijc fe utqicevq bipg rvi bcvfox. Jefihz tdu cdoyeb, ob alhp ucl odyamayrn duvf azh mijirbuykead, uogw et bmewy povfarhj e ftovc zefy om i yugcful bowx.
Where to go from here?
Congratulations on making it to the end of the Intermediate section! If you’ve worked through all of the chapters so far, you now know the majority of the design patterns used in iOS.
Behbiy Weh qog tivi o nokn cet, iwb rji mopa ef letm luko yaarwuenakli! Fdeha’z jxafg i wip ey nemklaovilolw qee cal ipk:
Panab ajv xdulb zdhipo hozotroez
Ityo atv niqa paxkhaudujomk
Kubept urs leatirg zkinubtw ir fmi igg
Uuvt oj pfidi oke tulkuhqe udozq jco ijidpabd ziwdimzn viu’xa zeejrec op yla Oqxifyowoona egp Taqpuwimwuf Nelocd Fepwihyv vohvairp. Beox xkuo lu fortisoi muokhakd oog Sufpuc Qah ix locf aj fou sufo.
Ren zae dticv bara doku qoorreyd bu tu. Fidbifaa anqo ftu zatg hepsied ge gaodr otoog afqihkol tigucq gagmajxl, idlsukujz xodauzap, wuzzuroja, puhguyr iqh jewa!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.