/home/wpollock1/public_html/AJava/AlertDemo.java
// This is a demo of the State design pattern. This class
// changes how it sends alerts depending on its state.
//
// Written 4/2021 by Wayne Pollock, Tampa Florida USA
public class AlertDemo {
Alerter alerter; // The state object; we forward "sendAlert" calls to it.
Person recipient; // To whom we send alerts
public AlertDemo (Alerter alerter) {
this.alerter = alerter;
}
// Change the demo objects state
public void setAlertMethod (Alerter alerter) {
this.alerter = alerter;
}
public boolean sendAlert (String message) {
this.alerter.sendAlert(message); // Forward method call to state object
return true;
}
public static void main ( String[] args ) {
Person recipient = new Person("Hymie", "piffl@example.com", "555-1212");
AlertDemo demo = new AlertDemo(new SMSAlerter(recipient));
demo.sendAlert("Data Center on fire");
demo.sendAlert("Security breach detected");
demo.setAlertMethod(new EmailAlerter(recipient));
demo.sendAlert("Data Center on fire");
demo.sendAlert("Security breach detected");
}
}
/**
* Send an alert message when something happens.
* @param message the message to send
* @return true if message was successfully sent, else false
*/
interface Alerter {
boolean sendAlert (String message);
}
/**
* Sends and SMS (text message) alert to recipient's phone
*/
class SMSAlerter implements Alerter {
Person recipient;
SMSAlerter ( Person recipient ) {
this.recipient = recipient;
}
@Override
public boolean sendAlert (String message) {
System.out.println("*** Sent Text message ***"); // Stub
return true;
}
}
/**
* Sends an email alert to the recipient's email address
*/
class EmailAlerter implements Alerter {
Person recipient;
EmailAlerter ( Person recipient ) {
this.recipient = recipient;
}
@Override
public boolean sendAlert (String message) {
System.out.println("*** Sent email message ***"); // Stub
return true;
}
}
class Person {
String name;
String email;
String phone;
Person ( String name, String email, String phone ) {
this.name = name;
this.email = email;
this.phone = phone;
}
// Getters, toString, ...
}