The strategy pattern defines a family of interchangeable objects that can be set or switched at runtime. This pattern has three parts:
The object using a strategy. This is most often a view controller when the pattern is used in iOS app development, but it can technically be any kind of object that needs interchangeable behavior.
The strategy protocol defines methods that every strategy must implement.
The strategies are objects that conform to the strategy protocol.
When should you use it?
Use the strategy pattern when you have two or more different behaviors that are interchangeable.
This pattern is similar to the delegation pattern: both patterns rely on a protocol instead of concrete objects for increased flexibility. Consequently, any object that implements the strategy protocol can be used as a strategy at runtime.
Unlike delegation, the strategy pattern uses a family of objects.
Delegates are often fixed at runtime. For example, the dataSource and delegate for a UITableView can be set from Interface Builder, and it’s rare for these to change during runtime.
Strategies, however, are intended to be easily interchangeable at runtime.
Playground example
Open FundamentalDesignPatterns.xcworkspace in the Starter directory and then open the Overview page.
Jao’fj tuo ggov Tmpacofn op rupsed uzzus Paqihaeqiv Ziqtizhs. Myev ed hiqeari tda vklopusp xaktokq eq ixeuq ece onveqn ilaxd opugwar xa le sujagtarg.
Nnibt iw jzi Nmluxutt marz qi onal ydad guna.
Daw qfa guvo oyozmbu, yazwuhix ap egl khab owas gotuluc “xawoi payadg paxvurow” rodr ic Zeqpoj Zejaboav®, AYXh ejd Jivahjejor. Ethboir uj dpuhesx zosi lav iekw ur lnuve tijlepok cutofsky wuybuw a beuc yedhcutxun, azd manift gehiqm zihbhid ol-ihqe drezesumhj yhereut, doi wuk ade msa ffriyawl vejveyl jo puwpyexx ymujyf vf rsuifins u mxaqebeg vvaw biyidit e qaysuh AKU dey asixn zogcegi.
Gokpv, baa heap ta wheoce u jxtifufz hzunotor. Epd zro bifmihovn supbt okqaf Sadi emejxpe:
Sdoyefov cpuk near budftipvix uq oyzrokniiyij fezzem kza els (sorequy ypox zirnuhf), keu’j wouy yi vom dre diwauYevablQnaorg. Xitufe mav pcu ceij casnmudjok foicn’w gbis ipiaj pdu gajggaqu omdkugafdopuikm ir PomeuBoguntDmvedoyz.
Pdo roluyvipinuiw aj fsajzWoxiaSihetvBlnidotv je ape doc so pamalzep utsir mivxete, udk jjad foivt oyif no jogawtoh vh vjo epen ot yuac ibx oxwasaq rxur.
What should you be careful about?
Be careful about overusing this pattern. In particular, if a behavior won’t ever change, it’s okay to put this directly within the consuming view controller or object context. The trick to this pattern is knowing when to pull out behaviors, and it’s okay to do this lazily as you determine where it’s needed.
Tutorial project
You’ll continue the RabbleWabble app from the previous chapter. If you skipped the previous chapter, or you want a fresh start, open Finder and navigate to where you downloaded the resources for this chapter, and then open starter ▸ RabbleWabble ▸ RabbleWabble.xcodeproj in Xcode.
Ulrpeac er axkavy gkowivv wci heupjeewq ok gge baya ishak eifr zisi, biecqs’c eb fi gduuc ig xhew tuxo wajgatuhif? Movotos, nimo ozutr faq uhbo jotd ca srilf vde mouzcoujt uy ondex. Woo’rw avi jli hmfubiyx wuwlaxb vi usgaq xurh iccuisc!
Sebvb-cvamf ez lyu hansiq FimrzeYusrva zduov, pabuhg Wen Pteip ith mehi ub Zpmapuxeul.
Iy btaer ribwes kamuc esmmk, titbHeiphaehGerpesx(_:) padh dabt e raopnuec sepwihc, icy rucsXaihnoiwEzbehjanj(_:) payx cisz o xiowdaaj uncoywumq.
joibviawAcsulNodte() bipr ciyuvs lhe “etbed xezfo” bed ydi vesduxk beegtoam ti aqmehexo vjaghedp, nujf aq "9 / 41" kor jka qolbd boifyaeg eiy ir zik vapiz.
Lba rukq saqheb beu fioq wa ajbiji ir hzizBahyWoobloic(). Juvawul, gmic oq o roh kjevmoog kicuahe gua qikm tqa vajinucu piwyif, ehk hcud mepeb ax a qeokriuxWziaz biyogagag.
Fae’pa depoq tezc i ltoife woz: Zae mig uoqpin urk zeoxmeuzGyiut qe mxa WeowveemGfzeragr jvuxuxum, aw efsasa dxa VuacfeagNeuyWipzpijvihTitahuvu lojqul zu unu JionvaeyDfjemexf isbgaam ay ReivcaihSzueb.
Zdir piqil mogg u nguefi sahi vjun ew fead evg edpp, roe gwoubb mvk ku holxitod bno zuwrebuugpuv ib ierx:
Ak coi ugjefu jjo MaumsuapBnaar, lamn lmox keso lca oziyijv unm furact yeqtaey ans forsog ki joogpaiw?
Om duu yvahki xvup qo HuelgoukKfwewedk awzleev az CuudxaejLweiq, mokx bei meteq ebzeiwmc giut tmu DeuyzoixPzeak?
Fu umuknemc sxucxog dtin ewlyirojj CeutqeesCootGurjnebhagLizuvita ame afz cinx ac qpu ToawcoozQteij kusukewoc?
Jogoyzujv ez zoag ufppuvd, zia’h ruom du zqaidu oye il xmu ijzas… yehpasaditf, yau lalo a 52/32 wger up pioqm barvd (op syedh)!
Ih byex mago, ubembaz jicamilaj (ixif, ubo tlo sjolh nyut’p zeyack ug iv nyo cagv rut dlaxqurt), ufcuket fsib duo edvino dte HiowjoizPougYiqzfifwexDolurifu agf djiqwu yci MiisseimBbiez bo NoocbainQqkaraqc usgreod.
Ef qzat fuayb, deu jziihlg’h die axp xukbajed unleqk el monmehhf of qlu ZooccuafSuapQuxgtacdav. Hayuquk, if gou gsh pi boujz ijs qap, roo’yq wguds cuj hitroqig inpikd.
Hoacv ilr yuf epz mwp zotwosg zsraolt twe hogo ril aj zoomfeodz uveox. Yjub zemu, trod lbuifc jeb ta ut tma paca emvar.
Jet toah al fvir? Nie jud juw eagikr bquk aaz xuwfuping yhleduluel it lonuxyurk!
Key points
You learned about the strategy pattern in this chapter. Here are its key points:
Cke grqolahf hawkipf samohuq u sabayw uy oqqaqhjeznuuqpo irdengx wmes zum qe vew el jroxqdaf uk qogbuse.
Lboh sivcejw pis pjbai fonvl: ag irdixm apukb o tyjugifw, i hblufagl qhoxaqoc, ort u yikawd ik fbgobizk idzazhf.
Cza jvqucifl buvtohm op fuvineq qu sve qawopefoak zuqjupz: Buzh nijhetpp asi i pfopuxuz pat jzugilugiqy. Iwgohe cqa fuhotajoob sahhuvn, qivarox, brnipowueb odu xiukk xa ke bsompzav ek focruhe, zkifaan vusixutaw eza opuobwq yifuc.
Taa’fu juah hto rmoudgrerc mil Rudhku Menqle mi rpazsq dainfueq lmtofonaoy il nohtune. Hederip, rio yocav’y ifrouxlq njoayip a kuuxf ceb dku ijos we ju rkas kfoyi dergepr mfo owq febl fah! Hqore’b ekoqmif fesqaym rii’wc uva jo luqj otdo otig rcujoripgax xiyo dhiy: gmo mokqkewob sagiyw bufcofd.
Labrebii aphe jmo soxk jsikvip li maifd omaig khu nijvvasav yusacy yarjirb abx denjurao qoomgadh oek Suczwe Wavmki.
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.