zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    使用RabbitMq
    创建.NET core的守护进程
    nginx配置
    让.net core 支持静态文件
    关于sql中如何动态加WHERE条件
    CentOS上部署.net core
    chrom中 background 调用pop.js
    windows下安装redis
    sql server导出大批量数据
    python爬虫笔记
  • 原文地址:https://www.cnblogs.com/chucklu/p/10554094.html
Copyright © 2011-2022 走看看