• Category: structural
  • Type: object
  • Motivation: share common parts(pool to cache flyweights) of state between multiple objects instead of keeping all of the data in each object

diagram

// same characters(saved in flyweight factory's pool) draws in different color

let document = Document()
for charcode in 43...48 {
    document.insert(charcode)
}
document.print()
print("\n")

document.color = 32
for charcode in 43...48 {
    document.insert(charcode)
}
document.print()
print("\n")

document.color = 33
for charcode in 43...48 {
    document.insert(charcode)
}
document.print()
print("\n")
CDEFGH
CDEFGHCDEFGH
CDEFGHCDEFGHCDEFGH
processor characters: 6
protocol Glyph
{
    var charcode: Int {get set}
    func draw(color: Int)
}

// String(Character(UnicodeScalar(0x47)))
struct Character: Glyph
{
    var charcode: Int

    init(_ charcode: Int = 0) {
        self.charcode = charcode
    }

    func draw(color: Int) {
        let char =  "&#x\(charcode);".applyingTransform(.toXMLHex, reverse: true) ?? ""
        print("\u{001B}[0;\(color)m\(char)\u{001B}[0;0m", terminator: "")
    }
}
class Processor
{
    var characters: [Int: Character] = [:]

    func find(by charcode: Int) -> Character {
        if characters[charcode] == nil {
            characters[charcode] = Character(charcode)
        }
        return characters[charcode] ?? Character()
    }
}

class Document
{
    let processor = Processor()
    var symbols: [Character] = []
    var color: Int = 31

    func insert(_ charcode: Int)
    {
        symbols.append(processor.find(by: charcode))
    }

    func print()
    {
        for symbol in symbols {
            symbol.draw(color: color)
        }
    }
}