Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- // Using an interface with default behavior or a sealed hierarchy is cleaner in modern Java
- sealed interface TelemetryEvent permits LocationEvent, SpeedEvent {
- int id();
- int timestamp();
- String getSummary();
- // Combined Alert Management
- default Optional<String> getAlert() {
- return Optional.empty();
- }
- }
- record LocationEvent(int id, int timestamp, float lat, float lon) implements TelemetryEvent {
- @Override
- public Optional<String> getAlert() {
- if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
- return Optional.of("!!CORRUPTED COORDINATES!!");
- }
- return Optional.empty();
- }
- @Override
- public String getSummary() {
- return String.format("LocationEvent [id=%d]: lat=%.2f, lon=%.2f", id, lat, lon);
- }
- }
- record SpeedEvent(int id, int timestamp, float speed) implements TelemetryEvent {
- @Override
- public Optional<String> getAlert() {
- return speed > 110 ? Optional.of("!!SPEED TOO HIGH!!") : Optional.empty();
- }
- @Override
- public String getSummary() {
- return String.format("SpeedEvent [id=%d]: speed=%.2f", id, speed);
- }
- }
- interface NotifChannel {
- void notify(String message);
- }
- // Concrete Observers
- record SMSNotifChannel(String nr) implements NotifChannel {
- public void notify(String msg) { System.out.println("SMS to " + nr + ": " + msg); }
- }
- record EmailNotifChannel(String email) implements NotifChannel {
- public void notify(String msg) { System.out.println("Email to " + email + ": " + msg); }
- }
- class EventProcessor {
- private final List<NotifChannel> channels = new ArrayList<>();
- public void addChannel(NotifChannel channel) { channels.add(channel); }
- public void process(TelemetryEvent event) {
- // Handle Alerts
- event.getAlert().ifPresent(msg -> {
- channels.forEach(channel -> channel.notify(msg));
- });
- // Log Summary
- System.out.println(event.getSummary());
- }
- }
- public class Main {
- static void main(String[] args) {
- var processor = new EventProcessor();
- processor.addChannel(new SMSNotifChannel("123-456"));
- List<TelemetryEvent> events = List.of(
- new SpeedEvent(1, 1000, 30),
- new SpeedEvent(2, 1001, 150), // Should Alert
- new LocationEvent(3, 1002, 200, 45) // Should Alert
- );
- events.forEach(processor::process);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment