/**
* 当引用计数等于 0 时。
* @callback OnDisposeCallback
*/
/**
* @class RefCountObject
* 引用计数对象。
* @memberof THING
* @public
*/
class RefCountObject {
#refCount = 1;
/**
* 构造函数。
* @example
* // 创建一个引用计数对象
* let refObj = new THING.BASE.RefCountObject();
*
* // 设置释放回调
* refObj.onDispose = function() {
* console.log('对象已被释放');
* };
*/
constructor() {
// #region Overrides
/**
* 当引用计数等于 0 时。
* @member {OnDisposeCallback} onDispose
* @memberof THING.RefCountObject
* @instance
* @public
*/
// #endregion
}
/**
* 增加引用计数。
* @public
* @example
* // 创建引用计数对象
* let refObj = new THING.BASE.RefCountObject();
* console.log(refObj.refCount); // 1
*
* // 增加引用计数
* refObj.addRef();
* console.log(refObj.refCount); // 2
*/
addRef() {
this.#refCount++;
}
/**
* 释放引用计数。
* @public
* @example
* // 创建引用计数对象
* let refObj = new THING.BASE.RefCountObject();
* refObj.addRef(); // 引用计数为2
*
* // 设置释放回调
* refObj.onDispose = function() {
* console.log('对象已被释放');
* };
*
* // 释放引用计数
* refObj.release(); // 引用计数减为1
* refObj.release(); // 引用计数减为0,触发onDispose回调
*/
release() {
if (this.#refCount === 0) {
return;
}
this.#refCount--;
if (this.#refCount === 0) {
if (this.onDispose) {
this.onDispose();
}
}
}
// #region Accessor
/**
* 获取引用计数。
* @type {number}
* @public
* @example
* // 创建引用计数对象
* let refObj = new THING.BASE.RefCountObject();
*
* // 获取引用计数
* console.log(refObj.refCount); // 1
*
* refObj.addRef();
* console.log(refObj.refCount); // 2
*/
get refCount() {
return this.#refCount;
}
// #endregion
}
export { RefCountObject }