Java天气预报系统:使用接口和状态模式
public interface WeatherState {
void showState();
}
public class Weather {
private WeatherState state;
public void show() {
state.showState();
}
public void setState(WeatherState s) {
state = s;
}
}
public class CloudyDayState implements WeatherState {
public void showState() {
System.out.print('多云');
}
}
public class SunnyDayState implements WeatherState {
public void showState() {
System.out.print('晴天');
}
}
public class RainyDayState implements WeatherState {
public void showState() {
System.out.print('下雨');
}
}
public class Main {
public static void main(String[] args) {
Weather weather = new Weather();
WeatherState cloudyState = new CloudyDayState();
WeatherState sunnyState = new SunnyDayState();
WeatherState rainyState = new RainyDayState();
weather.setState(cloudyState);
weather.show(); // Output: 多云
weather.setState(sunnyState);
weather.show(); // Output: 晴天
weather.setState(rainyState);
weather.show(); // Output: 下雨
}
}
这段代码实现了一个简单的天气预报系统,使用了接口和状态模式:
WeatherState接口: 定义了显示天气状态的方法showState()。Weather类: 拥有一个WeatherState类型的状态变量,以及show()方法用于显示当前天气状态,setState()方法用于设置天气状态。- 具体的WeatherState实现类:
CloudyDayState,SunnyDayState,RainyDayState实现了WeatherState接口,分别代表多云、晴天和下雨三种天气状态。 Main类: 创建Weather对象和不同天气状态对象,演示如何切换和显示天气状态。
通过这种设计,我们可以轻松扩展更多天气状态,例如雪天、雾天等,只需创建新的 WeatherState 实现类即可,无需修改 Weather 类,提高了代码的可维护性和扩展性。
原文地址: https://www.cveoy.top/t/topic/CqR 著作权归作者所有。请勿转载和采集!