Java设计模式泛型化之状态模式

通常情况下,我们这么理解它:

当你有多个不同状态,且有复杂的变化的时候。这个模式可以帮助你把视线分离开。

它的结构是这样的:

一个抽象的状态类(通常是抽象类),这个抽象类中定义了一个统一的调用句柄(handler),而且它定义了一系列对应状态的行为;
几个实现类去继承这个抽象类
一个统一调用句柄(handler)
一个调用者

代码结构如下:

状态类的抽象类

public abstract class AbstractState {
    
    protected Context context;
    
    public void setContext(Context context) {
        this.context = context;
    }

    public abstract void doStateA();
    
    public abstract void doStateB();
}

具体的实现类

public class ConcreteStateA extends AbstractState {

    @Override
    public void doStateA() {
        System.out.println("Concrete A is doing state A.");
    }

    @Override
    public void doStateB() {
        System.out.println("Concrete A is doing state B.");
    }

}

public class ConcreteStateB extends AbstractState {

    @Override
    public void doStateA() {
        System.out.println("Concrete B is doing state A.");
    }

    @Override
    public void doStateB() {
        System.out.println("Concrete B is doing state B.");
    }

}

统一调用句柄(handler)

public class Context {

    public static final ConcreteStateA STATE_A = new ConcreteStateA();
    
    public static final ConcreteStateB STATE_B = new ConcreteStateB();
    
    private AbstractState state;
    
    public AbstractState getState() {
        return state;
    }
    
    public void setState(AbstractState state) {
        this.state = state;
    }
    
    public void doStateA() {
        this.state.doStateA();
    }
    
    public void doStateB() {
        this.state.doStateB();
    }
}

调用者

public class StateCaller {

    public static void main(String[] args) {
        Context context = new Context();
        context.setState(new ConcreteStateA());
        context.doStateA();
        context.doStateB();
        
        context.setState(new ConcreteStateB());
        context.doStateA();
        context.doStateB();
    }
}

那么,如何泛型化呢?

泛型化的代码如下:

状态抽象类

public abstract class AbstractState {
    
    protected Context context;
    
    public void setContext(Context context) {
        this.context = context;
    }

    public abstract void doStateA();
    
    public abstract void doStateB();
}

统一调用句柄(handler)

public class Context {

    public static final ConcreteStateA STATE_A = new ConcreteStateA();
    
    public static final ConcreteStateB STATE_B = new ConcreteStateB();
    
    private T t;
    
    public T getState() {
        return t;
    }
    
    public void setState(T t) {
        this.t = t;
    }
    
    public void doStateA() {
        this.t.doStateA();
    }
    
    public void doStateB() {
        this.t.doStateB();
    }
}

调用者

public class StateCaller {

    public static void main(String[] args) {
        Context context = new Context();
        context.setState(new ConcreteStateA());
        context.doStateA();
        context.doStateB();
        
        context.setState(new ConcreteStateB());
        context.doStateA();
        context.doStateB();
    }
}


你可能感兴趣的:(Java,设计,Java技术)