3

I'm currently reading a book on JS design patterns and would like some confirmation about something.
The following code is an illustration of the state pattern as illustrated by the book:

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;
})();

In the previous code snippet, BankAccountManager and GoodStandingState keep a reference to each other, creating a cycle.
As I've read, this doesn't pose a problem anymore because of the Mark-and-sweep algorithm that is used for garbage collection:

Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

Still, I wonder if passing this as argument, and binding it as a reference variable to the other object (that is referenced by the current object) is good practice or if it would still be better to avoid it. In another language that applies the reference counting algorithm for GC, I assume that the previous snippet could cause a memory leak.

Is it ok to apply this pattern, or is it still wiser to avoid it?

1
  • Did you find any solution for it? I mean what are your views? I am also looking for similar information about State pattern. Apr 11, 2018 at 9:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.