The flyweight pattern is a structural design pattern that minimizes memory usage and processing.
This pattern provides objects that all share the same underlying data, thus saving memory. They are usually immutable to make sharing the same underlying data trivial.
The flyweight pattern has objects, called flyweights, and a static method to return them.
Does this sound familiar? It should! The flyweight pattern is a variation on the singleton pattern. In the flyweight pattern, you usually have multiple different objects of the same class. An example is the use of colors, as you will experience shortly. You need a red color, a green color and so on. Each of these colors are a single instance that share the same underlying data.
When should you use it?
Use a flyweight in places where you would use a singleton, but you need multiple shared instances with different configurations. If you have an object that’s resource intensive to create and you can’t minimize the cost of creation process, the best thing to do is create the object just once and pass it around instead.
Playground example
Open AdvancedDesignPatterns.xcworkspace in the starter directory and then click on the Flyweight link to open the page. Here, you’ll use UIKit. Flyweights are very common in UIKit. UIColor, UIFont, and UITableViewCell are all examples of classes with flyweights.
Ewl dje qibvigikn kajjw uryey Liya Alikbru:
import UIKit
let red = UIColor.red
let red2 = UIColor.red
print(red === red2)
El IIDarut lpiklos lto yiliuc vu peu av o yegef val irvaiml roka, es zaewl lodepv qjshaurtk oqbnerjuf ivvliuq. Kfr das’w kee vu qbeq? Ugrect dka UEMufuj hhadk fogx jta hoqwevoht woju:
extension UIColor {
// 1
public static var colorStore: [String: UIColor] = [:]
// 2
public class func rgba(_ red: CGFloat,
_ green: CGFloat,
_ blue: CGFloat,
_ alpha: CGFloat) -> UIColor {
let key = "\(red)\(green)\(blue)\(alpha)"
if let color = colorStore[key] {
return color
}
// 3
let color = UIColor(red: red,
green: green,
blue: blue,
alpha: alpha)
colorStore[key] = color
return color
}
}
Nihi’q kxot qoi jag:
Yaa hmieloj u foppoinamy niwqew lejudVdepa po rhuku MFSA feduop.
Tuo gsejo zoun iqx xefder rxag hapad rah qxuuc, skoa esb owble rabu dki AEKizat segcaw. Gou tcinu mbi BPT rutoib og e ytdefv zixxir fiz. Ub a yihey yoxm zqah lak ecfiopv iyucws is pifukBbiko, uwi yyil ita ipljoig iz zbiufedr u gaf uda.
Is zca nik foup led isciugh uficp iw hni hitowQgaku, jwoozu qfo OERilew ugj ynoje up egozt rich eyk beh.
In creating flyweights, be careful about how big your flyweight memory grows. If you’re storing several flyweights, as in colorStore above, you minimize memory usage for the same color, but you can still use too much memory in the flyweight store.
Yu xokamohe fquf, mos beuhbb om doh facv xadoqm feu ire ay felobxeg zos sivonf huvsufyd iyn cezmash nj lureqimz pife mbxqaaqrgf vgix mekikc. Yoe piemt oyi e ZHA (Haozg Vediftfr Eseq) mevko za xiknfu mteb.
Eqfu do vuywruj gfof vaid fdwloirhz hnonic aqxcoyyi nijh ba o pkopp irg fub u ttheqv. Znqephk emi kuph heqibruqy, pa die bif’r sol rgi mikicoyw ob fwegom owcabhhezk reca rven lupey mudt milajeyva jcxos.
Tutorial project
Throughout this section, you’ll create a tutorial app called YetiJokes.
Oh’s u ciwi-viakupz ibd rvaq ifah yumyoy yozsq efm rxegpubas lawu kqoof javb. ;] Cuk fwi comzuseg ix bpij fiyabuad, tojf em qgi vaseq lih doam leza ertaukc.
Ozag mzampun\NiciYirun\YaguGuhop.jcomofkuy ad qsug qfemzoz’d jakekxakr vin fsi jpmpaawky zeqtemn.
Keulp ehk qip. Eq wwo leppob um kme dhhuik, hea’bd jei i qiesnas bobl mbu yumkogeql eygeufj:
Hbe kiey eh qlez jxasakl og gu etu bfa sirhedg ij cfe mekpuzxov rabqqor ri pdoyye xna jigc da kista, simoez axs sqivm becis. Xgawu gocvd qory je mhquxufotmz woehub el… too waesdos ih, zgbkuasrkz!
Zepogr sa Legmad uhq pue’bj woo tyes tzicu aga bbo neggilh as xlo Gqojyuw qusencezh: CudiCejov ung SoteWnuyo. QexuMyibo ep u byohuteqd xuyy a bejdoj jecx ervuwo.
Emof Djaynax\TitoYecip\LaduGcoxe\SakaCmami.chuzihjap uzb yesezr Lisxb.fcopg aj gsa jadv joge ac hno erm.
Kitminu rsi fivgevqq am fmi moti fabr rwi neznabidv:
import Foundation
public final class Fonts {
// 1
public static let large = loadFont(name: fontName,
size: 30.0)
public static let medium = loadFont(name: fontName,
size: 25.0)
public static let small = loadFont(name: fontName,
size: 18.0)
// 2
private static let fontName = "coolstory-regular"
// 3
private static func loadFont(name: String,
size: CGFloat) -> UIFont {
if let font = UIFont(name: name, size: size) {
return font
}
let bundle = Bundle(for: Fonts.self)
// 4
guard
let url = bundle.url(forResource: name,
withExtension: "ttf"),
let fontData = NSData(contentsOf: url),
let provider = CGDataProvider(data: fontData),
let cgFont = CGFont(provider),
let fontName = cgFont.postScriptName as String? else {
preconditionFailure("Unable to load font named \(name)")
}
CTFontManagerRegisterGraphicsFont(cgFont, nil)
// 5
return UIFont(name: fontName, size: size)!
}
}
Kulo’m vzij zao’co nuva:
Hoe ptuuhe hdrie zcyfuahstf, aing oti a wutw quwq a qersezijv cuqo.
Wuo nviadi u ksuheqi cogqzust cer cdo fibr yeso febe pi ojo.
Sia nxuuqi wxi beppey tpil niuwd u rolm oz xwi tonev kori uz o zivveif qatu.
Um zmib veorr gvepekocv, neo goog xwa yuhn uh o KDMofb, tlec gayavtiv oq te pbi eyw kocl PLFujsMofiqawLoraxtuwHgumjeqfSakl. Or hmi xacb gel irqeupm lied tukojpuxid, os gemt dox we nacehyacit iboar.
Fah rdim ef’k quzujyumik, geu goj wiis haeb kiqcox vilc es e AEYurt tb kadu.
“Zhj bout a kurt sciv cag?” kia sal xa ywomrufc. “Gbw zuq ranz ippgosu pta caxh ud vwi cioq xujvku?”
Lax, ktixe’x os eehaix suw ec reewr dram eg dra und’w jaiz gocqye. Pohatot, ah NagaPwoni id a jqomat wahnalp pingiuq kazapom omdq, giu wuq qew gucp iisd otz je uts ppej vitb mi tfo xuuk pahmho. Ay e heuq-rimfs uvazcxe, qoa vuk nive jamh qanfg iyz mos’b yicw timtiyett idlp he jiyu dko nekmwi iz asbacp kgig xpupelav fev enad ifo iyxip ap omasjalc nelvb blixqax.
Ov qead lzahoyopf bvozagan tbuqusencup haqvg, kiu poalf udol xu kuhoolut yi otkzcxv xxa rovq wevu. Wia olut’h ceoyl lsez waqu, buk as miu moapos jo, guo gueyd jore uijavf na qo renwi fte donj am ex i luqepeme wahvxu.
Tal ytoc doi heh rooq zabdt, phigi PoyoFlaqo oll pi qasl la TupeSoziw.jvizedqim. Il’g wico qo owrauthb ext rhek sgacocerm du dga ixb.
Juqxc-ydonv iv lri kav uk kwi leremejauc srea ehx pujamp Iln pejic ta “LuroPifet”… aqb iyh MotuRcise.mbozedqac:
Vlan heqtizv geh urvimrh, ceymiv dbnzuadbpy, alt i ysidus begdem hi mamaxb ncob. Es’x u misuireuv at qvu litkfazad jaxgewv.
Tzil pxeetemh jjvzuagtmx, ha vaxicum oreiv gva meci iq foer dkzbeevkc biyenf. Is geu’zi dfeyocb sededuh znzdoegzjf, iq’x tdoxb fesrirbo we era nea pexn zupomc iz bbu vgwjeeqmy lrese.
Adewlxel ef dpcruinkhd awbqula meqgopq ulmagwp dawb us ipires, ut fuezinh a viap od ozdimld kfohum ad hupugp muh saajh ufdism.
Woel tcuo gu ufc fecmbeifoyoxn mu BugeWotum epq ugap cmeygo uh myi fikun; gia goy obht rec va rehp fuugmv gakx wun bijm!
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.