利用软件设计模式,写一个红绿灯信号通行的代码
时间: 2023-06-05 20:07:11 浏览: 145
好的,根据你的要求,我可以为你提供一个利用状态模式实现红绿灯信号通行的示例代码,具体如下:
```java
// 定义红绿灯的三种状态:红灯、绿灯、黄灯
interface TrafficLightState {
TrafficLightState nextState(); // 获得下一种状态
void handleMessage(); // 处理当前状态下的操作
}
class RedLightState implements TrafficLightState {
@Override
public TrafficLightState nextState() {
return new GreenLightState();
}
@Override
public void handleMessage() {
System.out.println("当前为红灯状态,请不要通过交叉口!");
}
}
class YellowLightState implements TrafficLightState {
@Override
public TrafficLightState nextState() {
return new RedLightState();
}
@Override
public void handleMessage() {
System.out.println("当前为黄灯状态,请慢行通过交叉口!");
}
}
class GreenLightState implements TrafficLightState {
@Override
public TrafficLightState nextState() {
return new YellowLightState();
}
@Override
public void handleMessage() {
System.out.println("当前为绿灯状态,请通过交叉口!");
}
}
class TrafficLight {
private TrafficLightState state;
public TrafficLight() {
state = new RedLightState(); // 初始状态为红灯
}
public void nextState() {
state = state.nextState();
}
public void handleMessage() {
state.handleMessage();
}
}
public class Main {
public static void main(String[] args) {
TrafficLight trafficLight = new TrafficLight();
// 红灯状态
trafficLight.handleMessage(); // 输出 "当前为红灯状态,请不要通过交叉口!"
trafficLight.nextState(); // 将状态转变为绿灯
trafficLight.handleMessage(); // 输出 "当前为绿灯状态,请通过交叉口!"
trafficLight.nextState(); // 将状态转变为黄灯
trafficLight.handleMessage(); // 输出 "当前为黄灯状态,请慢行通过交叉口!"
trafficLight.nextState(); // 将状态转变为红灯
trafficLight.handleMessage(); // 输出 "当前为红灯状态,请不要通过交叉口!"
}
}
```
这是一个简单的示例代码,通过状态模式实现了红绿灯信号通行的逻辑。当然,实际上红绿灯信号通行的过程可能更加复杂,需要考虑到多个交通信号灯、各种交通情况等等。但这个例子可以帮助你更好地理解软件设计模式中的状态模式。
希望这个代码对你有所帮助!
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)