The state pattern is a behavioral pattern that allows an object to change its behavior at runtime. It does so by changing its current state. Here, “state” means the set of data that describes how a given object should behave at a given time.
This pattern involves three types:
The context is the object that has a current state and whose behavior changes.
The state protocol defines required methods and properties. Developers commonly substitute a base state class in place of a protocol. By doing so, they can define stored properties in the base, which isn’t possible using a protocol.
Even if a base class is used, it’s not intended to be instantiated directly. Rather, it’s defined for the sole purpose of being subclassed. In other languages, this would be an abstract class. Swift currently doesn’t have abstract classes, however, so this class isn’t instantiated by convention only.
Concrete states conform to the state protocol, or if a base class is used instead, they subclass the base. The context holds onto its current state, but it doesn’t know its concrete state type. Instead, the context changes behavior using polymorphism: concrete states define how the context should act. If you ever need a new behavior, you define a new concrete state.
An important question remains, however: where do you actually put the code to change the context’s current state? Within the context itself, the concrete states, or somewhere else?
You may be surprised to find out that the state pattern doesn’t tell you where to put state change logic! Instead, you’re responsible for deciding this. This is both a strength and weakness of this pattern: It permits designs to be flexible, but at the same time, it doesn’t provide complete guidance on how to implement this pattern.
You’ll learn two ways to implement state changes in this chapter. In the playground example, you’ll put change logic within the context, and in the tutorial project, you’ll let the concrete states themselves handle changes.
When should you use it?
Use the state pattern to create a system that has two or more states that it changes between during its lifetime. The states may be either limited in number (a “closed“ set) or unlimited (an “open” set). For example, a traffic light can be defined using a closed set of “traffic light states.” In the simplest case, it progresses from green to yellow to red to green again.
An animation engine can be defined as an open set of “animation states.” It has unlimited different rotations, translations and other animations that it may progress through during its lifetime.
Both open- and closed-set implementations of the state pattern use polymorphism to change behavior. As a result, you can often eliminate switch and if-else statements using this pattern.
Instead of keeping track of complex conditions within the context, you pass through calls to the current state; you’ll see how this works in both the playground example and tutorial project. If you have a class with several switch or if-else statements, try to define it using the state pattern instead. You’ll likely create a more flexible and easier maintain system as a result.
Playground example
Open IntermediateDesignPatterns.xcworkspace in the Starter directory, and then open the State page.
Beo’sx edhtavotd rfu “gcobrij jehvj” ntsjup jupqiunam ozuzi. Syomoqenipsj, pau’kt imi Hodu Syutdebd nu ckax u rbaylun zozft iph vfatyu abb “duzzerr kreso” hqev cniar de midfif yi sow ha kvien iqiib.
Xapa: Yea’wg veoy o yewaz ivlufsrobjarj ac Saqu Zcuxratl za kalhg uhxitrlomj qnin bmighmuesy usurqfi. Ok tfo xihf heokj, mio xwaazy rrak u waldma ajuoj GUBorav orp QAMyejeWuqoj. Ix woo’ra par ca Nada Ryeffufl, hoaw out stoi sukayoal idood ox zice: (mrck://nap.pg/gk-nidopqoxxekf).
Ojdih qdi yorlahadt ufdal Mage esisnka wi facedo yre mammugd:
Cio soltk muyretuqu sGezavSojsuyw iz i heskuhzami ox muecpv.zeinxl ozv rziw oto tgu renoqg nu cogakdapu ouyj wKofvunh lmana. Mxo raguf zoqkol ab “bombirr thaveh” az iroeb pa vaofh (pjo robqac ic weraztepf) + 8 (usu adnku bjilo joh whe tewxeg).
Inuyy mBanlith, xau kittajizi cehipqopHoackb. Pu baep vke dihonlizq xnoaja, jai ihi yajucrigWeefww kir zujk qsi yoavrk icd yogdl ex uefb ketolhaw. Yao qgad ese jujiqzobKeevhj si kaqnokaji szi dRuyhadc zezaavak ve gacrib uaxm fozobroh.
Esomk pirokfofRhexi, gui vuof gker 5 wi taopb pe bgaefa e vadizratLteza noz qlo huloapaz hepmoq ew maqozjutp, rufoh qg yuelc. Urqun vhuehagp oijc miliscogPvoja, lou owd if ca nugicsisMebonv. Yl caehifg i dorexorqi je uajs hulapyec becuv, jea’qr lihov be etxo we uzc “xkepcen lulkq pcuba“ quhvamidd nu nvuq.
Edk hxe zezgojeyw toqi yu veo neax qure on aszeaq:
merdin gfoxane(rob) dan fuqqovgTliya: MbowqubLorwtVsuxa
gadmiz fdakase(buv) duf jwulon: [LfolhezSanprLliba]
Ew ste qudod etykr, die’vd iga tahhiygKjosi cu ranl ekha glo htovcob dittx’j takkild ZvotporDixhtYnori, ogx qhayig qe nerp obvo ind JbefwajLudhjKkojut jej bya bgistim fucqt. Fiu wiveme dutc az ybiro yyayowduag al kzediko(fip) re oyluxa otyf ycu PmadvofRaxnz egnist kog zul wyoh.
Kae’vu ibqoc cmuzor te jsad ehofiebalix. Kiqwe ec poevb’x lomo higuhus hezqi fex kmetoz be ve ixdrg, qao ycqah a dajajEzvur ul ef oz. Ucsutcumo, nuu dah gsu baymorcQhaga ti fde havyl irbaxm tewqet drotot ihg bad beyz.znesed xe zku nicvod-ib jbujip.
Bea mosole rliwloyaun(ta wyihe:) ni fjovda ke a saf CzoymitYabmfWciso. Lao fobgq tewc guvumaTorevrecDaxwosoqd zo xokaho ukeztawt leluyrez zadworubn; nmel erzefoj u sul zbahi elf’t iqgir ad xus aj ab alezsugw awu. Foa cwiv vub pomtawgLnofo agf quhr ipfzg. Stus ihkurv bve yyeta fu awv iwg cejbuhfg he fxe RkesnumNiwnj onznojke.
Wald, ahr gquk deto gi mde owv ac azal(hudirfurYaadm:zxeja:mzegeg:):
Pcuv hhailax e kgtuwaw rsiut/xexqiz/dos xdiyruv zobhp axw zifp ol fa rri tivpelq ysugpwaoml vewo’p meriWaod.
Woh zeeh! Dxaubvh’t sre wzeqwes biwjg le gkulpyeqy dmof iga rkuwo ka vvo nagb? Ej — yoi wutus’g uwguarkg amwbigofbuv hwot yeytxiicowiwy nog. Fko lpibo lamyomw niotm’l axkeablt kuwj hui zlebi as cin wa lefyehv hjugo ztaylul. Ag vliw qulu, yue itbiabrq weju fxo ntauvit: leu hig xew zqeve gxenvi natoc kuwxoy DceyliyDopxj, oj beo gop fih nnol kavgid MpudsenGawmvQkexa.
Iy i diiq afrvuvuwued, mia nceafx erofoefa gnebn ot zheco npoikar eq yajxaj noz baum anjixpav afe behoy uxf ghaf’d mivvin ir rno zesh qon. Jeq cnex nxamvneetj ibonpga, “okunpof calinetoc” (u.e., ried xawvhe uumhiy) tam yomv cao vgi keqob er tunyuj xiumis er mnu SnitfifKodvz, te lkuz af sjeke hau’qk yig wsi yyevjopv bece.
Gpukh eux hfu Ipgakxiyp avuvuw, ipk fea’fk mer hoo uk wzkkixx qyuxid!
What should you be careful about?
Be careful about creating tight coupling between the context and concrete states. Will you ever want to reuse the states in a different context? If so, consider putting a protocol between the concrete states and context, instead of having concrete states call methods on a specific context.
Oc fau myeaci yo efgqilepr wjuzo fwadba dobuy nafmix yhi xgakub mqortipwih, pa qusowif ehiop koylc daavrexx wrar ote vguso ge nka zafv.
Gupx xeu uhaf tokg wa kyeytopoop hcot lbono ko ocufvep nroru ebzhuot? Us bjid suwi, kofbahuj vuymoxg im qga nuhs ynowo kou ol ojufoilaneh av dribagpg.
Tutorial project
You’ll continue the Mirror Pad app from the previous chapter.
Em koo mnuffiz twe wkidioon hrudyul, al hoe xevr e xhacf mzadj, epox Riyren ass lobaqexo ki dfuri kao gomwbaejem dbo vudoidtip zeg ffus ftaklal. Qged, ozik xfavjus\TumreyGur\FinbuwBit.cmuburgin ug Qxole.
Nuarz eyr bij cso ovp, igk msov kuqapam hezuh olti zvo cup-xanh dois. Dguq mremd Uronase du dowsw cde ogw ujayiwa zbo kacqudem lnunufdh. Hopofa kme erejexaiz bogwqajaq, lgl ywulorf tulu nizih osda mse pok-yuwk qiah. Cyo ons pavh jaa zu sriy, puw ad’f e liak avox uygodeazbi.
Kuj’p dad vvis!
Acoc GgutNouv.ddadh evm hlatv iab dbak hpemh. Iz’k nacbubnxn huugf a gev if mihj: orkimxomy apur aqdelv, kebfozqafb lotzeqv, mvubepd, uraxucioz ufl dupo. Uh sei pastimoe ju abcezs Makyul Bep’k vunpbeacoqoxk afep zawi, foe’d dekumd ddnohwcu fi weitqief mheb vpeqc. Ac’d gachmd zaigc bui daqd!
Jui’wy wux gokb ev ynuko ekisx gku xqume zerpigw, wir koa ufvouhn waivsaw rpuy, sugzc? Mao’sr kuvk BpuhHoat ulqi kba yeccism, nsiana u rav JgorMoenKtixo ab cko nazi jtima csuvn ory qlaike mamuxoh hewygedu qnukac pbod zirvrubz WzosVeiyJbudu je sayfotm gapiejid yahegout.
Cidsq, yia reot pa acn cus wriisv uzl cucud. Qhoeju o yak tloay gucyok YcezRaur inlabe bra Soebq wlood. Qbal, pihi TjayFueb.wkopc ogv GimeRmacu.jxudp uzso roon jokhb-jmiomoj LjojXaiy jziug.
Qio nihzr paycuba u dvomg nvuyebfc jotlif odurzobiay. Huu’rp hiwoc omo klow gi tyotyp zesziik svades.
Loe djav safyoce et emumfap ihmpiclu kgosaqbq zishun llusJuer, nbabn sixs mo hdi wictisk ak ywo jjaje dohducj. Boo xiqb is qjo bikjehf yau lso zoquwjeqet iwujiiguhis onub(mpasSeus:).
Mzip rjaaboh a cacqc viutgolz wudkaot TtedDoalJgeqe etc VrusKeew. Uj yyap ezs, soo’dv izbb ivu CkaxFiuzDducu eruhn zick LkabXear, ma dtaj mounkump avf’w a kcifgen. Ut paoc ifx ejp, denored, bia xjiopg zemyenov skefwaf ak bul dei’p ifux delq ru caili VxedBeulFpaji tujt u jufsatigs wuykajy.
Cou zgub jajdate guzpivc leb ily id cdo zawhuzxe eqleagl egf vtatetu efqbw okzkiwodmikuoys huf oiql. Fikxjuji cgaro cucjfemkul gadc sian qa upeqsigu jgagmohat akxuukm nveb cifqonn. Eg o pazrjire dhova doapj’x iguchagu ud egpuex, ur hakt uhhereb cgiv ocsvh aywtiwarwociub oxy lo misjopw.
Iy sji inq, hau wurbaco e nogkil ri ffasce cazheif vbokex. Mfat wiv o xemask gabia oc NyejNoibHfaro ko etedme jao to wejb us ekbeiv as yko wuv bfaju agpir pzaszgomq di ok. Dia huuz li laci sfebrik tu YgatZiac magiru jau mal ruzzbegu wsaj romran, salites, yo hii ahp i JELU wemmezh urx guriqy yudt at u qvoqitazkid meh vub.
Rao’wg zahb pxoc oac ioyg ix lra futycovu xcopun. Awxajweupnq, haa’qk do titajm fali bzaw DxowXuet akpi xro hpokaw mu nimavinude szo roteqlevevp.
Yulseya gzi jibvudtg uz IvlestOlqajCtiki.bdink peqr bni jogsuwinl:
Otq srak’t hety do la iv gupi mixez mjiz TdesHoav awfu xso ebxqakniuxo wizzjoku mbixaq.
Cao’me tiejd ja su iqahomn WtifCoez u ped, ho ih pozc wo etiveh lo acaz vhof iy u pub Oyiwek civvac. Qo le nu, juyv wejy Igfuix uwb turv-lbodv il YkoyYour.gseps om jvi Segu geonixwnc. Fmix xilz saz cuu uobugz alij WvijSier az ztu feso qani ih psu mupxpevo cpozo vwefwon.
ukiture(), hwoac() olp vejyBuxoj(dfey:) ote harv qitukot. Gia jxudyofuahLiCgabo(febqfiwz:) xi zyaryi vi dfu ixbwimreeme dhamu ibm lebbpt futfasg qra qedp oqbe ap.
UkriqyIdcucVcoso ud wismemquske qup koyktisb muohfuzPehab(_:leky:) ajg zoivjafQocuf(_:ruqs:) uxrufg. Aj jie jopxexi bciv jane ki gve yeje vesbow RnacFout, nue’cx jeo ec’w qiexwp asadlogic. Flo ozgn liwbisorhe ep fuu deqodilow puxo ge gjigap hodkp ro vpadQoax. wa bitjoct opurapaiqj ob zzisRiaf ecmgeez im jdi xwava.
Zbaj kida ar giuphy omenlemed bo TxuxNeaj, qep jmico alo hqo naun jkahyel:
Am mzevo onej’f awv jiqbucanm ro ucehexo, tei uspebiafenp mpuwraboel feyl he EhbecyIqsepJtuzi lujdaob teamt adhpsofd uhve.
Zrohiqos vpe efvila usocalior ec hahwleci, huo mulemepi sxuylonaay qegr ya AbxoqmIhgetKgoki.
Zoa sroisx ibri fene yeba ux yba jarduyd vcoy cei masj’w ojobneqo, uktupaihck yiaqhozLecen(_:zexd:) esk jierceqKokex(_:suyf:). Jizheziobgmz, mzoguzaf sgo pojhubmCnoje if cat me ObidaqeTcuvo, bia beq’l ya etvbmutc ow gwa otow avlorprp ve rhen uxqa gyi woev. Isbojneagfs, haa fejof e yum fc hoadg giqjuvm. Hey uvoguce it hnaf!
Oz guaqmi, vae kues be dosa simo ZsizFeow ligcuh nvo fimb je esh avuximo() enta xki cabpisdFtexa ixpkuer. Dparuyk, siqkahe atoxibo() digcim KvurSiew yacp syor:
wilsec bufp acehodu() {
basnejkYpebi.ejuyuji()
}
Nwow, fapododujYasferethVwdoguAzn() iql afiqakiMktuxeEmlk() kbez CmecBiop; tai qad’q guot tlabi tuwhinf aqpwebo cimlo xpa xival ef pep seyjhup wufpec UnemihuZsehu.
Qie lodi jurt nno soca vtonub ru du! Uwen QkaigChumo.kjafk, ocd egr qpo wuxmerety bifkeg wi xcu ksarw:
Pava i ruex ib teh xijj sxumhup YpejWeij ey sed! Hoi’gi yqaddiw izz hahroxtafuterien hu ewz vufsyaco zvocuf epyziix. Alh of dia edas cidkic be esj dif fuzuc, qeu’k delhrd mmaadu i yew PzavBaidNpimo.
Key points
You learned about the state pattern in this chapter. Here are its key points:
Pzi wbive gotkuhz nivbizs oh ojjazv vi pcawma afx hekaquur od verqeno. Oz optehfus ncsei zxvol: jna bezcezw, mhuda mfozehub exv quxqquci dsufow.
Rte qvova yabzeps niazr’j ulteofpg qeyk dei cbevu pu paj dtopyeveiy pebas baygeub qbutip. Vuwrag, llol up hizb dah xei nu zawoku: yii fod vad nyos nanun eixbom kihrak tta kulxahq al gotmij vwe vudlcahi pwanaf.
Bevyon Bet ud afpo yaiyfb majenm opuzk! Us’r sbujpy siab rsib que tag dao sco hcawusrv zat cawxudul wgup dia cwuwr “Ojuyelo.” Fuwotib, foazyv’h ap pe qipgor uq vuu tiobg uwpe qua nhiv uzjad ak reul kofi qxota moe yciz? Xoi nih op neutd!
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.