帮我写一个在MVC架构中获取天气的代码
时间: 2023-08-28 14:33:46 浏览: 46
好的,以下是一个简单的在MVC架构中获取天气的代码示例:
在模型层(Model)中:
```java
public class WeatherModel {
private String city;
private String weather;
public WeatherModel(String city) {
this.city = city;
}
public void getWeather() {
// 调用天气API获取天气信息
String weatherInfo = WeatherAPI.getWeatherInfo(city);
// 解析天气信息
this.weather = parseWeatherInfo(weatherInfo);
}
public String getCity() {
return city;
}
public String getWeather() {
return weather;
}
private String parseWeatherInfo(String weatherInfo) {
// 解析天气信息
// ...
return parsedWeatherInfo;
}
}
```
在控制器层(Controller)中:
```java
public class WeatherController {
private WeatherModel model;
private WeatherView view;
public WeatherController(WeatherModel model, WeatherView view) {
this.model = model;
this.view = view;
}
public void setCity(String city) {
model.setCity(city);
}
public void updateView() {
model.getWeather();
view.displayWeather(model.getCity(), model.getWeather());
}
}
```
在视图层(View)中:
```java
public class WeatherView {
public void displayWeather(String city, String weather) {
System.out.println("City: " + city);
System.out.println("Weather: " + weather);
}
}
```
这样,当用户在视图层中输入城市名称并点击“获取天气”按钮时,控制器层会根据用户输入的城市名称更新模型层中的城市属性,并调用模型层中的getWeather()方法获取天气信息,最后再将获取到的城市和天气信息显示在视图层中。