• What are the differences between Flyweight and Object Pool patterns?


     What are the differences between Flyweight and Object Pool patterns?

    They differ in the way they are used.

    Pooled objects can simultaneously be used by a single "client" only. For that, a pooled object must be checked out from the pool, then it can be used by a client, and then the client must return the object back to the pool. Multiple instances of identical objects may exist, up to the maximal capacity of the pool.

    In contrast, a Flyweight object is singleton, and it can be used simultaneously by multiple clients.

    As for concurrent access, pooled objects can be mutable and they usually don't need to be thread safe, as typically, only one thread is going to use a specific instance at the same time. Flyweight must either be immutable (the best option), or implement thread safety. (Frankly, I'm not sure if a mutable Flyweight is still Flyweight :))

    As for performance and scalability, pools can become bottlenecks, if all the pooled objects are in use and more clients need them, threads will become blocked waiting for available object from the pool. This is not the case with Flyweight.

    Flyweight vs object pool patterns: When is each useful?

    One difference in that flyweights are commonly immutable instances, while resources acquired from the pool usually are mutable.

    So you create flyweights to avoid the cost of repeatedly create multiple instances of objects containing the same state (because they are all the same, you just create only one and reuse it throughout all places in your app), while resources in a pool are particular resources that you want to control individually and possibly have different state, but you don't want to pay the cost of creation and destruction because they are all initialized in the same state.

  • 相关阅读:
    应用程序跳转
    百度地图集成
    导航 -MapKit
    导航
    定位
    ApexSql Log使用体会
    Oracle学习 第16天
    上来冒个泡吧
    Oracle学习 实战心得总结
    好久没上来冒个泡了,整整一个半月
  • 原文地址:https://www.cnblogs.com/chucklu/p/10554094.html
Copyright © 2020-2023  润新知