需求
动作 | 走状态 | 停状态 | 动作后状态 |
走行 | 不动作 | 走行 | 进入=>走行状态 |
停止 | 走行 | 不动作 | 进入=>停止状态 |
发射 | 辅助瞄准 | 精准瞄准 | 状态不变 |
测试用例
步骤 | 规格 |
初始化 | 停状态 |
停止 | 不动作 |
发射 | 精准瞄准 |
走行 | 走行 |
发射 | 辅助瞄准 |
走行 | 不动作 |
停止 | 停止 |
类图
1.标准类图
2.本实例类图
代码
class Function{
public String mStr;
Function(String str){
mStr = str;
exe();
}
public void exe() {
System.out.println(mStr);
}
};
// 坦克
interface IStateTank{
//走
void run();
//停
void stop();
//射击
void shot();
}
// 上下文
interface IContext{
void changeState(IStateTank state);
void run();
void stop();
void shot();
}
///* abstract *//////////////////////////////////////
abstract class State implements IStateTank{
IContext mContext;
protected State(IContext c) {
mContext = c;
}
}
///* Concrete *//////////////////////////////////////
class RunStae extends State{
static IStateTank mStateTank = null;
private RunStae(IContext c) {
super(c);
}
public void run() {
new Function("机能不运行:走行==走行");
}
public void stop() {
mContext.changeState(StopStae.getRunState(mContext));
System.out.println("变更:走行=>停止");
}
public void shot() {
new Function("辅助瞄准");
}
static IStateTank getRunState(IContext c) {
if(mStateTank == null) {
mStateTank = new RunStae(c);
}
return mStateTank;
}
}
class StopStae extends State{
static IStateTank mStateTank = null;
private StopStae(IContext c) {
super(c);
}
public void run() {
new Function("走行机能运行");
mContext.changeState(RunStae.getRunState(mContext));
System.out.println("变更:停止=>走行");
}
public void stop() {
new Function("机能不运行:停止==停止");
}
public void shot() {
new Function("精准瞄准");
}
public static IStateTank getRunState(IContext c) {
if(mStateTank == null) {
mStateTank = new StopStae(c);
}
return mStateTank;
}
}
class ContextTank implements IContext{
IStateTank mState;
public ContextTank(){
mState = StopStae.getRunState(this);
}
public void changeState(IStateTank state) {
mState = state;
}
public void run() {
mState.run();
}
public void stop() {
mState.stop();
}
public void shot() {
mState.shot();
}
}
class A{
static A ma;
static public A get() {
return ma;
}
}
public class Client {
public static void main(String[] args) {
System.out.println("hello worldff !");
ContextTank tank = new ContextTank();
tank.stop();
tank.shot();
tank.run();
tank.shot();
tank.run();
tank.stop();
}
}
运行结果
说明
专题模式中state类Context类间的关系可以有多种处理方式,这里采用了单实例的方式来实现。
因为单实例没有什么太多可说的,即使+线程等各种情况,这也就是个需求而已。
没有太多的设计价值可体现,所以就在这里运用了一下作为举例了。