import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// Observer Interface
interface Observer {
void update(String weather);
}
// Subject Interface
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// ConcreteSubject Class
class WeatherStation implements Subject {
private List<Observer> observers = new ArrayList<>();
private String weather;
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(weather);
}
}
public void setWeather(String newWeather) {
this.weather = newWeather;
notifyObservers();
}
}
// ConcreteObserver Class
class PhoneDisplay implements Observer {
private String weather;
@Override
public void update(String weather) {
this.weather = weather;
display();
}
private void display() {
System.out.println("Phone Display: Weather updated - " + weather);
}
}
// ConcreteObserver Class
class TVDisplay implements Observer {
private String weather;
@Override
public void update(String weather) {
this.weather = weather;
try {
display();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void display() throws IOException {
FileWriter fileWriter = new FileWriter("weather.txt",true);
fileWriter.write("TV Display: Weather updated - " + weather+"\n");
fileWriter.close();
// System.out.println();
}
}
// Usage Class
public class WeatherApp {
public static void main(String[] args) {
WeatherStation weatherStation = new WeatherStation();
Observer phoneDisplay = new PhoneDisplay();
Observer tvDisplay = new TVDisplay();
weatherStation.addObserver(phoneDisplay);
weatherStation.addObserver(tvDisplay);
// Simulating weather change
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("please input temperature now, input enter to exit");
String info = scanner.nextLine();
if(info.equals("")){
break;
}
weatherStation.setWeather(info);
}
System.out.println("over");
// Output:
// Phone Display: Weather updated - Sunny
// TV Display: Weather updated - Sunny
}
}
07-16
3835
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-04
1759
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-17