天气可能出现不同的状态,要求用接口封装天气的状态。具体要求如下: 1、编写一个接口WeatherState,该接口有一个名为void showState()的方法。 2、编写Weather类,该类中有一个WeatherState接口声明的变量state。另外,该类有一个show()方法,在该方法中让接口state回调showState()方法。该类中还有一个setState(WeatherState s)方法,用于设置state的状态。 3、编写2个实现WeatherState接口的类 CloudyState类,重写接口方法,输出“天气多云,最高温度28度,最低温度20度” SunnyState类,重写接口方法,输出“天气晴朗,最高温度32度,最低温度25度” 4、编写主类E,在主类中进行天气预报。 如:Weather nanchang=new Weather(); nanchang.setState(new CloudyState()); nanchang.show(); nanchang.setState(new SunnyState()); nanchang.show();
时间: 2024-02-20 18:59:44 浏览: 43
好的,我明白了您的问题。下面是实现您要求的代码:
```java
// 定义接口WeatherState
interface WeatherState {
void showState();
}
// 实现接口WeatherState的CloudyState类
class CloudyState implements WeatherState {
public void showState() {
System.out.println("天气多云,最高温度28度,最低温度20度。");
}
}
// 实现接口WeatherState的SunnyState类
class SunnyState implements WeatherState {
public void showState() {
System.out.println("天气晴朗,最高温度32度,最低温度25度。");
}
}
// 定义Weather类
class Weather {
private WeatherState state; // 定义WeatherState接口声明的变量state
// 定义setState方法,用于设置state的状态
public void setState(WeatherState s) {
this.state = s;
}
// 定义show方法,在该方法中让接口state回调showState()方法
public void show() {
state.showState();
}
}
// 主类E
public class Main {
public static void main(String[] args) {
Weather nanchang = new Weather();
nanchang.setState(new CloudyState()); // 设置为多云状态
nanchang.show(); // 输出天气状态
nanchang.setState(new SunnyState()); // 设置为晴朗状态
nanchang.show(); // 输出天气状态
}
}
```
您可以使用上述代码进行天气状态的封装和预报。希望能够帮到您!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)