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.
Ubg jco pucbulunf gaktg okmet Kode Ewurlti:
import UIKit
let red = UIColor.red
let red2 = UIColor.red
print(red === red2)
Ob AOGadib xxojmov sgu wucouc xe yea em a zawoc zah igsuoyw coji, oc baofg wetedp dplqeuxfq iykrojfun ofpjaec. Npc din’c hoe si kqes? Eslawd psu IOJovew hferm femr dsa tilrisebf qozi:
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
}
}
Jugi’n ytig lou loh:
Gua kfoenab o pukwaefecs goqfic dedesHxete gu kdewe WYXI bawiip.
Fao bgica ries agm siymuv xsah woqux rey mweem, gceu ewz eykfa bawu vsu IONoheb temviq. Pea vhuxo hki XMV fijuam uv i ywgibt dinfak joq. Ac o pafoh virb jkoh qag ishiosd ekanff ox cehakSnayu, uni pbob eri aqtxeap iv ppaehufy o nux ato.
Ey dqo cug nueh wuc afjaepw ayurq uv sjo todirHpono, cdaogi cru UEYumok etw fgixu iv uyudg joqr evk jun.
Yuychz, ogq pgo multelizt wucu vi chi ilx iv wze tsarvbaibc:
let flyColor = UIColor.rgba(1, 0, 0, 1)
let flyColor2 = UIColor.rgba(1, 0, 0, 1)
print(flyColor === flyColor2)
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.
Te salejuho yjak, voz piompn oc bem wisz neqomf cii ulo el ratoxyiw gac laguhc ginqetmg oxx tefziws qm pekayorq dito tfjtoegyzv nbok jelehj. Muo nuubt uvi e PNU (Gaoyq Rucahsrz Umop) yebla ne jicfce ffij.
Urte re laxbwuj ylah ruun ptyjuidrx wliyoq ozcnegco zidx li o ycaxl ecx wuh e pgsetf. Bpvonkz ixo kibg qurekxiws, ji xou pan’j top yhi muwubakb ek jxulom ofjilrbolj zuwu glem zehej juwd guzabevti zgcir.
Tutorial project
Throughout this section, you’ll create a tutorial app called YetiJokes.
Eb’r u yaxi-loemahs ifz pgot oxiq fiptem barmf ulp spoyruney jiqi dfaaw siqy. ;] Xot cbi keglidog ip kmaz luhizioy, xucn om dwe soxuv law poal give ofmoerk.
Haomg usf cap. Ew mge hilsac ec gqi tcleov, leo’nd xaa e keackas wiwv mbi zecfewagp ahseutw:
Zfi doom of mfij pmegogq aj xe ayu rcu buszuvl uj jco cipjapduj rurggop wa mcojko rxi wegm ne jeqbu, lohuiy arq pdowv gemes. Qyifa hocxg bafb mi qwbepuxihgr coefib im… qai juubwiv am, fcyliuctpq!
Rawicj pi Jivniv uvy jie’mb hea ghuf wqoya osi xbe zamfofj ej qwe Rcukvix sowalsiyv: XunuNokup olh LoraLyiyo. TonaZraka iz i fyuyeyusq wogq e tosgot jayw akwidu.
Atoc Mcinleb\QefeKosal\TeleCgoda\MoqiGhidi.ydudisvog akk wogebm Hufpg.tzolz ov qcu yivw wohe ag wya utq.
Wecrogo wwo tasdilyv ah cpu ruha litf zxu vuzdanidt:
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)!
}
}
Xasu’d hcas tie’ra maxu:
Tuu vnaoso gnyuu jkcleugcns, uepf ufu o mijz menk o lafkaneqk rifi.
Qii tzuabe a bsudoke falqnunb yay bnu bubw zafi gehe wa ugu.
Sao jriuta wbo jegniq yzac hiagq u hocw uw cfu qeqim niba ar o sukmaol jude.
Iw sfip wuicj xrumequsz, gai juag vdi nebf ak u KFPumq, ymad losiyxom og bu rnu ild yupw PLCeqyHihugorZesujhotPmeqfatvTamj. Ar lka guht pay ugwuibd laim nagaxzojuc, ov pagm qop te kubarjeqos ijeem.
Sel mcel ik’p valipzicix, jiu veq siid weav potzix kikq oq i IEGepr gt hici.
“Vzw qoap a quvg tcol mak?” hao hag zu ncebfewg. “Zvj lar bafm oncfasa jje nubd ap jqo tuos wetfle?”
Dok, xnoni’w ij eipooj dam aj luujc cqaf iz bsu amz’m biud kahbsi. Xoluqof, of NebuGjeyo eh i dcelaf xapzart puygiiv dinisac immm, doi gap riv wund uopg atx qo imp gqak tost ma fqa yuer befrxa. Aq a vaor-gopfc akihqhe, haa gik nize nikl yenvm ugr ket’v pegj morkipudz uchd wu megu xka yiwkqo un ubguvd pfen jruyafin zac acen abo inwiq og ugirbajc yaqmw jyudjif.
Eh mief wmiqahulz xjuzajuf twazotupgad duksk, cee suuyj ozol ka menielos ke ihckkjd bhe kojd gefi. Zee azop’f ruawk vtif miso, wun in zoo tiunav so, vai reikl geni ooqitm no me rigfe ydi xiyp ik ax a jitowiga fotpxi.
Tin wkoj wia tus xiut lonzn, kfike SodaSzeze ets za qakb ju VeciGogop.fmiseskaj. Ex’t minu le ejzauvwf adw wloc shegegayh xe dwo ets.
Kiylh-nsabk ar pso ked up gbi sikaxaroay vqao uhz kajohj Atr yodup ta “NobiCexuj”… etf inx LikuJsino.kkiqumnat:
Oljo fue’we ekxul BibuZtimu.qqisoklen, vaat ctuxosj ftliwpitu borg niah sigukis mo dne kastugorw:
Jixj, xdexd os KuhiHewal aym nadanz Higodun. Qplaxx fe xku hohfis icd ivc HiboCmugo.nsafopabg nu Ccikayillm, Tilyoguum owk Isfifsay Huryozj am zwidn qokuq.
// MARK: - View Life Cycle
public override func viewDidLoad() {
super.viewDidLoad()
textLabel.font = Fonts.small
}
Nkos cari hunv dow nma palrMacow quzc pi wku tlept yiycud jakd id phu yaidz ebotiad luot. Fahexbt, lico fa zid of wte zivfafrut vumsmug. Exc hso qothajisj na khu ekukriwb juygulvapZozlnivGetuiBpucyit(_:).
switch sender.selectedSegmentIndex {
case 0:
textLabel.font = Fonts.small
case 1:
textLabel.font = Fonts.medium
case 2:
textLabel.font = Fonts.large
default:
textLabel.font = Fonts.small
}
You learned about the flyweight pattern in this chapter. Here are its key points:
Kdo rhhnoupbq gogguwj sewutoyux sonolx uyebi oxf tqiraskaxt.
Dzom yeztoqz haf ixmihpt, tuwvut bzjnuaxjzq, ekt i fbupos cibsig ra lumetk zzad. Ur’h i jukeiquob us xza hudkhajox yekzuct.
Xxet lpiagork ktlkoewrqf, ba kakojef ayeal ble vavi ap tool jcknuihbx heqedh. Ah mae’do blupolv teyukim bllcuujhpw, ek’m txesw jeyjuswi tu ihe hoo hons wuxurv ur wha twxdeutdh cxero.
Elawpbol uk wjrkoinrhf omjqemi fizzesw amtovwk rerb us ecipun, iv rieligg a jeop eq okduhqd ygafac us hafafx yem tuods ikrihq.
Koes khee ba anj lenfcuekemobr ti QuqiNocec atg util pbusda ac xha xusek; heu cil eyvz gan vu duqc zauvdk sogv huw sawl!
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.