
//ConcreteState
function CloseState() {
this.open = function(c) {
console.log("open the connection");
c.setState(new OpenState());
}
this.close = function(c) {
console.log("connection is already closed");
}
}
//ConcreteState
function OpenState() {
this.open = function(c) {
console.log("connection is already open");
}
this.close = function(c) {
console.log("close the connection");
c.setState(new CloseState());
}
}
//Context
function Connection() {
var state = new CloseState();
this.open = function() {
state.open(this);
}
this.close = function() {
state.close(this);
}
this.setState = function(sState) {
state = sState;
}
}
//Client
var con = new Connection();
con.open();
//printed: open the connection
con.open();
//printed: connection is already open
con.close();
//printed: close the connection
con.close();
//printed: connection is already closed