对象池(Object Pool)模式

对象池模式适用于当对象的创建代价比较高又需要频繁创建的时候。对象池模式会创建一批对象缓存起来待用。当需要对象的时候就从缓存池中获取,不需要的时候就放回缓存池中。当缓存池中对象不够用的时候又会创建新的对象放到缓存池中。

类图如下:


代码如下:

/**
 * 
 * Oliphaunts are expensive to create
 *
 */
public class Oliphaunt {

  private static int counter = 1;

  private final int id;

  /**
   * Constructor
   */
  public Oliphaunt() {
    id = counter++;
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public int getId() {
    return id;
  }

  @Override
  public String toString() {
    return String.format("Oliphaunt id=%d", id);
  }
}
/**
 * Generic object pool
 * @param <T> Type T of Object in the Pool
 */
public abstract class ObjectPool<T> {

  private Set<T> available = new HashSet<>();
  private Set<T> inUse = new HashSet<>();

  protected abstract T create();

  /**
   * Checkout object from pool
   */
  public synchronized T checkOut() {
    if (available.isEmpty()) {
      available.add(create());
    }
    T instance = available.iterator().next();
    available.remove(instance);
    inUse.add(instance);
    return instance;
  }

  public synchronized void checkIn(T instance) {
    inUse.remove(instance);
    available.add(instance);
  }

  @Override
  public String toString() {
    return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
  }
}
/**
 * 
 * Oliphaunt object pool
 *
 */
public class OliphauntPool extends ObjectPool<Oliphaunt> {

  @Override
  protected Oliphaunt create() {
    return new Oliphaunt();
  }
}

  private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

  /**
   * Program entry point
   * 
   * @param args command line args
   */
  public static void main(String[] args) {
    OliphauntPool pool = new OliphauntPool();
    LOGGER.info(pool.toString());
    Oliphaunt oliphaunt1 = pool.checkOut();
    LOGGER.info("Checked out {}", oliphaunt1);
    LOGGER.info(pool.toString());
    Oliphaunt oliphaunt2 = pool.checkOut();
    LOGGER.info("Checked out {}", oliphaunt2);
    Oliphaunt oliphaunt3 = pool.checkOut();
    LOGGER.info("Checked out {}", oliphaunt3);
    LOGGER.info(pool.toString());
    LOGGER.info("Checking in {}", oliphaunt1);
    pool.checkIn(oliphaunt1);
    LOGGER.info("Checking in {}", oliphaunt2);
    pool.checkIn(oliphaunt2);
    LOGGER.info(pool.toString());
    Oliphaunt oliphaunt4 = pool.checkOut();
    LOGGER.info("Checked out {}", oliphaunt4);
    Oliphaunt oliphaunt5 = pool.checkOut();
    LOGGER.info("Checked out {}", oliphaunt5);
    LOGGER.info(pool.toString());
  }
}




猜你喜欢

转载自blog.csdn.net/THEONE10211024/article/details/77713949
今日推荐