Java设计模式之状态模式

[color=red]STATE[/color] (Object Behavioral)
[color=red]Purpose[/color]
Ties object circumstances to its behavior, allowing the object
to behave in different ways based upon its internal state.
[color=red]Use When[/color]
1 The behavior of an object should be influenced by its state.
2 Complex conditions tie object behavior to its state.
3 Transitions between states need to be explicit.
[color=red]Example[/color]
An email object can have various states, all of which will
change how the object handles different functions. If the state
is “not sent” then the call to send() is going to send the message
while a call to recallMessage() will either throw an error or do
nothing. However, if the state is “sent” then the call to send()
would either throw an error or do nothing while the call to
recallMessage() would attempt to send a recall notification
to recipients. To avoid conditional statements in most or all
methods there would be multiple state objects that handle the
implementation with respect to their particular state. The calls
within the Email object would then be delegated down to the
appropriate state object for handling.

package javaPattern.state;

public interface State {
public void handle(Context context);
}

class ConcreteStateA implements State{

@Override
public void handle(Context context) {
//在A中设置B状态
context.setState(new ConcreteStateB());
}

}
class ConcreteStateB implements State{

@Override
public void handle(Context context) {
//在B中设置A状态
context.setState(new ConcreteStateA());
}

}
class Context {
private State state;

public State getState() {
return state;
}

public void setState(State state) {
this.state = state;
System.out.println("当前设置的状态是"+state.getClass().getName());
}

public Context(State state) {
this.state = state;
}
public void request(){
this.state.handle(this);
}
public static void main(String[] args) {
Context context = new Context(new ConcreteStateA());
context.request();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值