享元模式参考:JAVA享元模式
简说设计模式——享元模式
Pool, SimplePool与SynchronizedPool
项目里频繁新建对象,容易对内存造成损耗,所以用到对象池来管理生成的对象,用完以后回收到对象池,下次要用的时候再捞出来重置数据并使用。
例子:
public class MsgRemindBean {
private boolean isShow;
private String content;
private String type;
public boolean isShow() {
return isShow;
}
public void setShow(boolean show) {
isShow = show;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
//对象池
private static final Pools.SynchronizedPool<MsgRemindBean> sPool = new Pools.SynchronizedPool<MsgRemindBean>(1);
//获取对象中数据
public static MsgRemindBean obtain() {
MsgRemindBean acquire = sPool.acquire();
if (acquire == null) {
return new MsgRemindBean();
}
return acquire;
}
//回收对象
private void recycle() {
sPool.release(this);
}
//设置对象内部数据
private void setBeanData(boolean isShow, String content, String type) {
this.isShow = isShow;
this.content = content;
this.type = type;
}
public static void sendMsgRemindBean(boolean isShow, String content, String type) {
MsgRemindBean bean = obtain();
bean.setBeanData(isShow, content, type);
EventBus.getDefault().post(bean);//这里我做了发送Eventbus,也可以换成别的逻辑,使用新生成的对象
bean.recycle();
}
}