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.

  • 相关阅读:
    javascript 心得
    pdfbox加载pdf时遇到wrappedioexception报错处理方式
    缩写
    Java学习——连接数据库
    oracle 关于null值排序
    Java学习笔记(二)
    kvm安装windows系统
    导入excel文件信息
    shell脚本根据端口号自启动jar
    spirngboot使用netty实现UDP协议接收数据
  • 原文地址:https://www.cnblogs.com/chucklu/p/10554094.html
Copyright © 2011-2022 走看看