一、UML图
二、代码示例
package com.designPattern.State;
/**
* Created by ZhangJintao on 2020/7/9.
*/
public class Car {
private CarState carState = null;
public Car() {
this.carState = new CarStopState();
}
public void start() {
carState.start(this);
}
public void stop() {
carState.stop(this);
}
public void setCarState(CarState carState) {
this.carState = carState;
}
}
package com.designPattern.State;
/**
* Created by ZhangJintao on 2020/7/9.
*/
public interface CarState {
public void start(Car car) ;
public void stop(Car car) ;
}
package com.designPattern.State;
/**
* Created by ZhangJintao on 2020/7/9.
*/
public class CarStartState implements CarState {
@Override
public void start(Car car) {
System.out.println("汽车已经启动了!不能重新启动。");
}
@Override
public void stop(Car car) {
System.out.println("开始停车,同时将汽车状态修改为停止!");
car.setCarState(new CarStopState());
}
}
package com.designPattern.State;
/**
* Created by ZhangJintao on 2020/7/9.
*/
public class CarStopState implements CarState {
@Override
public void start(Car car) {
System.out.println("开始启动汽车,同时将汽车状态修改为启动!");
car.setCarState(new CarStartState());
}
@Override
public void stop(Car car) {
System.out.println("汽车已经停了!不能重复停。");
}
}
package com.designPattern.State;
/**
* Created by ZhangJintao on 2020/7/9.
*/
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.stop();
car.stop();
}
}
三、运行结果