享元设计模式

百花池例子.

FlowerView类

class FlowerView: UIImageView {

    override func draw(_ rect: CGRect) {
        image?.draw(in: rect)
    }
}

FlowerFactory类

class FlowerFactory: NSObject {

    var flowerPool: [String: FlowerView] = [:]
    
    func flowerViewWithType(type: FlowerType) -> UIView {
        
        var flowerView = flowerPool[type.rawValue]
        if flowerView == nil {
            let flowerImage = UIImage(named: type.rawValue)
            flowerView = FlowerView(image: flowerImage)
            flowerPool[type.rawValue] = flowerView
        }
        return flowerView!
    }
}

FlyWeightView类


class FlyWeightView: UIView {

    var flowerList: Array = [ExtrinsicFlowerState]()
    override func draw(_ rect: CGRect) {
        for state in flowerList {
            state.flowerView.draw(state.area)
        }
    }
}

客户端代码

 override func viewDidLoad() {
        super.viewDidLoad()
        let factory = FlowerFactory()
        var flowerList = Array()
        
        for _ in 0..<500 {
            var types = [FlowerType.one, FlowerType.tow, FlowerType.three]
            let type = types[Int(arc4random() % 3)]
            let flowerView = factory.flowerViewWithType(type: type)
            let bounds = UIScreen.main.bounds
            let x = arc4random() % UInt32(bounds.width)
            let y = arc4random() % UInt32(bounds.height)

            let minSize: UInt32 = 10
            let maxSize: UInt32 = 50
            
            let size = (arc4random() % (maxSize - minSize + 1)) + minSize
            
            let extrinsicState = ExtrinsicFlowerState(flowerView: flowerView, area: CGRect(x: Int(x), y: Int(y), width: Int(size), height: Int(size)))
            flowerList.append(extrinsicState)
        }
        
        (self.view as! FlyWeightView).flowerList = flowerList
    }

结果如下:


result

GitHub地址

你可能感兴趣的:(享元设计模式)