Flyweight

godo·2022년 8월 18일
0

Swift - Design Patterns

목록 보기
10/24

저장 공간을 효율적 사용 할 수 있게 하는 기술로 연관 되거나 비슷한 객체들을 활용합니다.

Repeating User Names

class User
{
    var fullName: String
    
    init(_ fullName: String)
    {
        self.fullName = fullName
    }
    
    var charCount: Int
    {
        return fullName.utf8.count
    }
}

class User2
{
    static var strings = [String]()
    private var names = [Int]()
    
    init(_ fullName: String)
    {
        func getOrAdd(_ s: String) -> Int
        {
            if let idx = type(of: self).strings.firstIndex(of: s)
            {
                return idx
            } else
            {
                type(of: self).strings.append(s)
                return type(of: self).strings.count - 1
            }
        }
        
        names = fullName.components(separatedBy: " ").map { getOrAdd($0) }
    }
    
    static var charCount : Int
    {
        return strings.map { $0.utf8.count }.reduce(0, +)
    }
}

func main()
{
    let user1 = User("John lennon")
    let user2 = User("Jane fowel")
    let user3 = User("Jane Doe")
    
    let totalChars = user1.charCount + user2.charCount + user3.charCount
    print("Total number of chars used: \(totalChars)")
    
    let user4 = User2("John lennon")
    let user5 = User2("Jane fowel")
    let user6 = User2("Jane Doe")
    print("Total number of chars used: \(User2.charCount)")
}

Text Formatting

extension String
{
    func substring(_ location: Int, _ length: Int) -> String?
    {
        guard self.count >= location + length else {return nil}
        let start = index(startIndex, offsetBy: location)
        let end = index(startIndex, offsetBy: location + length)
        return substring(with: start..<end)
    }
}

class FormattedText: CustomStringConvertible
{
    
    private var text: String
    private var capitlize : [Bool]
    
    init(_ text: String)
    {
        self.text = text
        self.capitlize = [Bool](repeating: false, count: text.utf8.count)
    }
    
    func capitalize(_ start: Int, _ end: Int)
    {
        for i in start...end
        {
            capitlize[i] = true
        }
    }
    
    var description: String
    {
        var s = ""
        for i in 0..<text.utf8.count
        {
            let c = text.substring(i, 1)!
            s += capitlize[i] ? c.capitalized : c
        }
        return s
    }
}


class BetterFormattedText: CustomStringConvertible
{
    private var text: String
    private var formatting = [TextRange]()
    
    init(_ text: String)
    {
        self.text = text
    }
    
    func getRange(_ start: Int, _ end: Int) -> TextRange
    {
        let range = TextRange(start, end)
        formatting.append(range)
        return range
    }
    
    var description: String
    {
        var s = ""
        for i in 0..<text.utf8.count
        {
            var c = text.substring(i, 1)!
            for range in formatting
            {
                if range.covers(i) && range.captialize
                {
                    c = c.capitalized
                }
            }
            
            s += c
        }
        
        return s
    }
    
    class TextRange
    {
        var start, end: Int
        var captialize = false
        
        init(_ start: Int, _ end: Int)
        {
            self.start = start
            self.end = end
        }
        
        func covers(_ position: Int) -> Bool
        {
            return position >= start && position <= end
        }
    }
}


func main()
{
    let ft = FormattedText("This is a new world")
    ft.capitalize(5, 10)
    print(ft)
    
    let bft = BetterFormattedText("This is a new world")
    bft.getRange(5, 10).captialize = true
    print(bft)
}

정리

  • 공통된 데이터를 이용하여 공간을 효율적으로 활용하는 방식
  • 범위를 정해서 공통된 데이터를 결정함
profile
☀️☀️☀️

0개의 댓글