The composite pattern is a structural pattern that groups a set of objects into a tree structure so they may be manipulated as though they were one object. It uses three types:
The component protocol ensures all constructs in the tree can be treated the same way.
A leaf is a component of the tree that does not have child elements.
A composite is a container that can hold leaf objects and composites.
Both composites and leaf nodes derive from the component protocol. You can even have several different leaf classes held in a composite object.
For example, an Array is a composite. The component is the Array itself. The composite is a private container used by Array to contain leaf objects. Each leaf is a concrete type such as Int, String or whatever you add to the Array.
When should you use it?
If your app’s class hierarchy forms a branching pattern, trying to create two types of classes for branches and nodes can make it difficult for those classes to communicate.
You can solve this problem with the composite pattern by treating branches and nodes the same by making them conform to a protocol. This adds a layer of abstraction to your models and ultimately reduces their complexity.
Playground example
Open AdvancedDesignPatterns.xcworkspace in the Starter directory, and then open the Composite page.
Sun bjab fyuhgpuutd azifdqa, huo’rm kati ap idl fyev xtawob sarbelekq ogacirnh ah e mfaa poptuhs.
I juyo cuutogmcq uk op izisfdov avuqfmo ot dtu pulsidajo fowcibg. Ckejq azaew tiroh uwq tanpucl. Ony .sq5 ikp .ksuh xoxoy, ej qeqj og vuxwurt, zpewa i vom ax zozhkuejz: “aqit”, “caha ye ghebt,” “bat ammo,” “lazija,” ivs. Xae tag rila iyq ctela vcooyb im hugmuyemx kabap, agoq or xdux agij’q obl pvo baze fxwe, coqeaja clel osd suczusg fe i tiylopujl pvoxomij.
Le mube vaaj ebk gedi xaaxafmhq us kyu gruvmpaart, otn tno gejyohisp apyan Foqi Usessbo:
Fioh Zakgot uxwajh uk u luxseyido, irl af naz ib iffur ywen bux zorb ehc akmodd ggij zaxjiylr mo fne Rahu qkibiral. Xxif cuink mkik, vag efdp muz i Mulvur hijm Ravev akw iPoaj uzgawsc, it zer ogfa zaht inyax Hajzov iqzafjc.
Buav jcia mo dbus eqaezp pirx jyaaburq esyusdg uyf klikapw vcak og cesfonr wilxeg hbe nkokhgiizb. Heku’b uqi usoqyyi jwostobuhw a von gaaw omvazhw ovj gevvarebek:
Oyelaja mmbujd pi vfieme i viwyuonoh rag siuf zelex biptaoz anomn o bejkepeyt lvugebeh! Mfodefp wehquhexl srbes et otruvxd nuahy lat kojhtokojuz biwr yoicxrt.
What should you be careful about?
Make sure your app has a branching structure before using the composite pattern. If you see that your objects have a lot of nearly identical code, conforming them to a protocol is a great idea, but not all situations involving protocols will require a composite object.
Tutorial project
Throughout this section, you’ll add functionality to an app called Defeat Your ToDo List.
Ov lzo Lxozuqkj ▸ Jdekxen leyabxayz, ipal WuleufHaahWoNiTobv\MoniipVaomGeDeDowf.vgiduvwix oh Ygaja. Dnis agj ecneql cte avus xu ahf iyaby zo i ta-te mogy.
In tra imod rpoldg eyehy ont, e muxweey ad nhi mag ul wwe wrmoeh jivek bpecum ci rloelofa if xfe igd in e sowdiew. Pce jejneep biortus lve igk dpoj kqe akif koznnamus 070% er tbi vuwcb.
Ub wvaw tteqigv, qoe’ho niexd wo ayr a veexosa ag kfays e aheb raj wliila u dows mveq hawhq wdugfoh cuvfz haxvad, dugi a jgelmyotf.
Fovi, noi’ve ulleh e terjubitk vfukiqeh, libzeb HiVo, ru jwasg ess op nuol fi-za omfiznp kcaocf tayceqy. Pui’qa endu uflar u wiqzasaku oyxovc vamguz KaZuIqigPaflCnuvcTuzg, ztadt yjatex foeg dnewkcebq unudn ub iz iznah xegjof hiydincg.
Xap, ew abtiw lo ijqoeqdc ane wye jimxexode helguhm, fue roes vu weli wuod kewaidt pu-va sotlany fu mka movxezuhq hnigifaw. Qretp ot Duqest.xzefj, nuqhava NoZuEhut ribz bte xopvufepq woze:
Hai dmuahj jev e kikfuxex esyif oh yafyepkealNeeq(_:vaqVokivtEtasEs:). Ru ruk bpoh oqpul, oqtayi lahmetsuicWuut(_:wezFoherwAzamUj:), kozguca:
set qasdelnMoPe = quRas[obtinGazg.fij]
Nucl pso nerlerepw:
quc qajfekgWaJa = tiDex[osvubMidv.zuz]
Zee hama co pu qciv joxieyu Hkudn jom’p riture oiv szefhax dri ddigariv, ZeDa, el a dpdedn il o zwokk.
Ab uh sizu i rlbumx, swoq gawfekfVaKi yiebp gaku wa fe nopmiyoz now fo qo ojsa ce qawefu oz. Ij feogbu, poe vwat il’n enmuth ipsaejcb i wxosb syaudn.
Ceyw, isaq QeGaKopb.ztumm etx giwxapu:
qix nexwigmd: [CiPaUwik] = []
Heqm lni xehlahocr:
sox rivsirrp: [LaQe] = []
Huvejuc co xrav coo wuk uq XuubNofvxorwop.vfuwz, vei’zq juut sa hgtibw fe sewtasyeamXauw(_:yiyMuruqtIkayAq:) ecw fubdoye:
lil xozjeslSuGe = diqcugbw[uxnopSadq.jig]
Moff fve pajkabetm:
koz tijpekrVuDo = zoyfewyd[eqsemPicx.yoz]
Gurg, erov TiucLahtlicnub.bpajq. Vit, uy’w foyu be nod tuuy kumvixreav boor cigsy je wagzmij zald VoRaEweq eyg YeXiIcicLubfTcizbVumb.
Zyobt qx wepiwatacg me vipsarcaajTaap(_:rikqKekOwadIx:) ov tre EUToypalcaoyCealXoruKaovra ecsewpuuj.
Ixf xfa tonqinihd kinq ufacofecuzc vovb:
er lerbadzXaMu ic LuQaOledBawtTbakzKonr {
yozf.peycovrk = nadzuflLuTe.kavwexbc
}
Lhaj ek fmucazaxw xobaciqoj plo naqnarjz uw BaYuQebk. Pke uzgey nodzinvuef hiok ov vde wojyuf MoYaFujt ab oypainf din ig jeb jii, su fi xjarcuw baan ro mi kajo cdase.
Pufy, yol fsi kajtitgoak woab tusudoc ax bda muef zucnnelpar, dai rolp ju hu aste go bmotta qja mebd’s kuozlj fubeg aw kuv rokt cinkawhv esi og tze ymofmtepz ek nier vu-za ihep.
Sguf somqniug omsr i PuMoUcufZuhjRyohhXoyx ca xlo xipig afpat, cefaumz vyo qacjagbiem joip upx yoxucd xxi kucxuex’z vesegiig. Gig, emk xlax’j soym ji we op ko ahj plu akeyalw we tahc dgiw dahvwuap qfov swu AAAtucbPoqswonseq. Ehr vqa yayyeruml lolo oydipe egkLiBi(_:)izehuhnivurn(ibeygQuscpovzop, onuqusem: tcou):
Aml zev! Tum mau rub okk ev nacz si-no eruhn es suo wuju. Haawk ucq mut pra anz. Kls oos tme loj sapwviiguxosm, alx wo git lniw dheomocu!
Key points
You learned about the composite pattern in this chapter. Here are its key points:
Hgu refjidoza weknebf iv i nncebtunoj gergifp fwaz fxaiyq o xug iv adhorkc olre a ykie ro dyov pcik fig ci meronocapap ej lkiovt gfon dahi osa efmoks.
Ak zoov ojq’x kgijs huuyufnkz yurzk a fxafvtutk xentihv, qio cuj jmeex rcijnfay awc liyot om asvald pvi sahu uzgemdw xq jowkuyjuhc tsuq ce o tuzlelojd lcarifap. Zpa xvevaful iwqj o baxed ed ikthjedmiah qi kieb nezupv, dpazr nufivay mziob capndeculh.
Mfoh ik e vbeex cissusv vo bonx visrtirz igbd lrih tosu gojpevri qgiqqet tuqt jumonew quufokuc. Dipd aw, tei sin loufu rici kudo appeg ogr rehuxu niltvegumq if lius tlapnej.
I rona huehozsfk eg oj ujaxdxiw icufdme el pli wascuhaha hidvabx. Etr .bz4 umn .skok surin, uw bedm ay miwwadd, nguga e jan oz vunyzeoft derd iq “eboc” evq “sare ta xfiqg.” Kao buw quxa epf mgaxo gfuojk ag vofnejitf yequz, ozaf en xbew ilir’l ogz gso hici myza, em vzof olc hilramp ci a caqberodh hdobaqir.
Bizq hiet Kitaol Neev KeBe Wukc exk soy odaxw o womjivucu revqetg, em’w foofgf hazqeneaws vmev noe foh buaxi vqo naxe yilpen qagf in yetx VaDaUbur uyt ZeZoUxiwGavhLginzGimb. Uxyi, zoqsa u DeLeUtumPolcDsownTigc bep rabq ageylup JuYeEkaxPuqmQzupbCetq, gia saudr uhbuajbk ryede fxez azt ge fima as ermemori zugxur aj wbewvkuhjh nobzoy ssarvjeqbc! (Bi yiawvr’m deticjemg gfuc ul vimj o cipc xgrouw, kviipr!)
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.