Javascript 国家模式良好实践?
我目前正在读一本关于JS设计模式的书,希望得到一些确认。Javascript 国家模式良好实践?,javascript,garbage-collection,Javascript,Garbage Collection,我目前正在读一本关于JS设计模式的书,希望得到一些确认。 以下代码是本书所示状态模式的说明: var BankAccountManager = (function () { function BankAccountManager() { this.currentState = new GoodStandingState(this); } BankAccountManager.prototype.Deposit = function (amount) { this.cur
以下代码是本书所示状态模式的说明:
var BankAccountManager = (function () {
function BankAccountManager() {
this.currentState = new GoodStandingState(this);
}
BankAccountManager.prototype.Deposit = function (amount) {
this.currentState.Deposit(amount);
};
BankAccountManager.prototype.Withdraw = function (amount) {
this.currentState.Withdraw(amount);
};
BankAccountManager.prototype.addToBalance = function (amount) {
this.balance += amount;
};
BankAccountManager.prototype.getBalance = function () {
return this.balance;
};
BankAccountManager.prototype.moveToState = function (newState) {
this.currentState = newState;
};
return BankAccountManager;
})();
var GoodStandingState = (function () {
function GoodStandingState(manager) {
this.manager = manager;
}
GoodStandingState.prototype.Deposit = function (amount) {
this.manager.addToBalance(amount);
};
GoodStandingState.prototype.Withdraw = function (amount) {
if (this.manager.getBalance() < amount) {
this.manager.moveToState(new OverdrawnState(this.manager));
}
this.manager.addToBalance(-1 * amount);
};
return GoodStandingState;
})();
var BankAccountManager=(函数(){
职能银行账户经理(){
this.currentState=新货物标准状态(this);
}
BankAccountManager.prototype.Deposit=函数(金额){
本.现状.存款(金额);
};
BankAccountManager.prototype.Draw=函数(金额){
本.currentState.Draw(金额);
};
BankAccountManager.prototype.addToBalance=函数(金额){
此余额+=金额;
};
BankAccountManager.prototype.getBalance=函数(){
还这个。结余;
};
BankAccountManager.prototype.moveToState=函数(newState){
this.currentState=newState;
};
返回银行账户经理;
})();
var GoodStandingState=(函数(){
功能良好状态(经理){
this.manager=经理;
}
GoodStandingState.prototype.Deposit=函数(金额){
此.manager.addToBalance(金额);
};
GoodStandingState.prototype.draw=函数(金额){
if(this.manager.getBalance()
在前面的代码段中,BankAccountManager
和GoodStandingState
相互引用,创建一个循环。正如我所读到的,这不再是一个问题,因为用于垃圾收集的标记和扫描算法: 垃圾收集器将定期从这些根开始,查找 从这些根引用的所有对象,然后是所有对象 从这些引用,等等。从根开始,垃圾 收集器将因此找到所有可访问的对象并收集所有 无法到达的对象 不过,我想知道将
这个
作为参数传递,并将其作为引用变量绑定到另一个对象(当前对象引用的对象)是一种好的做法,还是最好还是避免它。在另一种为GC应用引用计数算法的语言中,我假设前面的代码段可能导致内存泄漏
应用这种模式可以吗,还是更明智地避免它 你找到解决办法了吗?我是说你的观点是什么?我也在寻找关于状态模式的类似信息。