Open
Description
状态模式
定义:
当一个对象内在状态改变时允许其改变行为,这个对象看起来像改变了其类
状态模式的核心是封装,把事物的每种状态都封装成单独的类,和此种状态有关的行为都被封装在这个类的内部
状态模式是一种非常优秀的模式,也许是解决某些需求场景的最好方法。
实现
JavaScript
// 状态模式
var Light = function() {
this.offLightState = new OffLightState(this);
this.weakLightState = new WeakLightState(this);
this.strongLightState = new StrongLightState(this);
this.button = null;
}
Light.prototype.init = function() {
var button = document.createElement('button');
var self = this;
this.button = document.body.appendChild(button);
this.button.innerHTML = '开关';
this.currentState = this.OffLightState;
this.button.onclick = function() {
self.currentState.buttonWasPressed();
}
}
Light.prototype.setState = function(newState) {
this.currentState = newState;
}
var State = function(){};
State.prototype.buttonWasPressed = function() {
throw new Error('buttonWasPressed不能缺失');
}
var OffLightState = function(light) {
this.light = light;
}
OffLightState.prototype = new State();
OffLightState.prototype.buttonWasPressed = function() {
console.log('弱光');
this.light.setState(this.light.weakLightState);
}
var WeakLightState = function(light) {
this.light = light;
}
WeakLightState.prototype = new State();
WeakLightState.prototype.buttonWasPressed = function() {
console.log('强光');
this.light.setState(this.light.strongLightState);
}
var StrongLightState = function(light) {
this.light = light;
}
StrongLightState.prototype = new State();
StrongLightState.prototype.buttonWasPressed = function() {
console.log('关灯');
this.light.setState(this.light.offLightState);
}
Java
/**
* 具体环境角色
**/
public class Context {
public final static State STATE1 = new ConcreteState1();
public final static State STATE2 = new ConcreteState2();
// 当前状态
private State CurrentState;
public State getCurrentState() {
return CurrentState;
}
public void setCurrentState(State currentState) {
CurrentState = currentState;
CurrentState.setContext(this);
}
public void handle1() {
this.CurrentState.handle1();
}
public void handle2() {
this.CurrentState.handle2();
}
}
/**
* 抽象状态类
**/
public abstract class State {
protected Context context;
public void setContext(Context context) {
this.context = context;
}
// 行为1
public abstract void handle1();
public abstract void handle2();
}
/**
* 具体状态类
**/
public class ConcreteState1 extends State{
@Override
public void handle1() {
// 本状态下必须处理的逻辑
}
@Override
public void handle2() {
super.context.setCurrentState(Context.STATE2);
super.context.handle2();
}
}
public class ConcreteState2 extends State{
@Override
public void handle1() {
super.context.setCurrentState(Context.STATE1);
super.context.handle1();
}
@Override
public void handle2() {
}
}
/**
* 实现类
**/
public class Client {
public static void main(String[] args) {
// 定义环境角色
Context context = new Context();
context.setCurrentState(new ConcreteState1());
context.handle1();
context.handle2();
}
}
Metadata
Metadata
Assignees
Labels
No labels