知道Factory类的一般设计模式是这样的:
class Element {
constructor();
destructor();
}
class Factory {
static function createElement() {return new Element();}
}
并且它的典型用例看起来像这样:
Element x = Factory.createElement();
...
x.destructor();
而且我知道,通常在声明x.destructor()
的作用域的末尾隐式调用x
(或在实现垃圾回收器的虚拟语言中,只要GC确定x
为不再使用)。
但是假设我们根本没有析构函数,就像Javascript一样。
然后我一直在考虑使用以下设计模式:
class Element {
constructor();
function destructor();
}
class Factory {
static function createElement() {return new Element();}
static function destroyElement(Element x) {x.destructor();}
}
然后,它的典型用例如下所示:
Element x = Factory.createElement();
...
Factory.destroyElement(x);
与“传统”设计相比,此设计模式有什么缺点吗?
谢谢!
虽然这在很大程度上是个人观点,但是在JavaScript之类的语言中,我发现析构函数是多余的。