美文网首页
EventBus中的享元模式

EventBus中的享元模式

作者: 石器时代小古董 | 来源:发表于2018-11-04 22:37 被阅读0次

减少对象的创建频率
1.首先准备一个对象池缓存对象
2.如果缓存中存在对象

private static final int POOL_SIZE = 4;
  private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
   //取出数据对象
    private  FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        findState.recycle();
      //准备数据对象
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        return subscriberMethods;
    }

   FindState findState = prepareFindState();

相关文章

网友评论

      本文标题:EventBus中的享元模式

      本文链接:https://www.haomeiwen.com/subject/yfuhvftx.html