AlertDemo.java
Download AlertDemo.java
1: // This is a demo of the State design pattern. This class
2: // changes how it sends alerts depending on its state.
3: //
4: // Written 4/2021 by Wayne Pollock, Tampa Florida USA
5:
6: public class AlertDemo {
7: Alerter alerter; // The state object; we forward "sendAlert" calls to it.
8: Person recipient; // To whom we send alerts
9:
10: public AlertDemo (Alerter alerter) {
11: this.alerter = alerter;
12: }
13:
14: // Change the demo objects state
15: public void setAlertMethod (Alerter alerter) {
16: this.alerter = alerter;
17: }
18:
19: public boolean sendAlert (String message) {
20: this.alerter.sendAlert(message); // Forward method call to state object
21: return true;
22: }
23:
24: public static void main ( String[] args ) {
25: Person recipient = new Person("Hymie", "piffl@example.com", "555-1212");
26: AlertDemo demo = new AlertDemo(new SMSAlerter(recipient));
27: demo.sendAlert("Data Center on fire");
28: demo.sendAlert("Security breach detected");
29: demo.setAlertMethod(new EmailAlerter(recipient));
30: demo.sendAlert("Data Center on fire");
31: demo.sendAlert("Security breach detected");
32: }
33: }
34:
35: /**
36: * Send an alert message when something happens.
37: * @param message the message to send
38: * @return true if message was successfully sent, else false
39: */
40: interface Alerter {
41: boolean sendAlert (String message);
42: }
43:
44: /**
45: * Sends and SMS (text message) alert to recipient's phone
46: */
47: class SMSAlerter implements Alerter {
48: Person recipient;
49:
50: SMSAlerter ( Person recipient ) {
51: this.recipient = recipient;
52: }
53:
54: @Override
55: public boolean sendAlert (String message) {
56: System.out.println("*** Sent Text message ***"); // Stub
57: return true;
58: }
59: }
60:
61: /**
62: * Sends an email alert to the recipient's email address
63: */
64:
65: class EmailAlerter implements Alerter {
66: Person recipient;
67:
68: EmailAlerter ( Person recipient ) {
69: this.recipient = recipient;
70: }
71:
72: @Override
73: public boolean sendAlert (String message) {
74: System.out.println("*** Sent email message ***"); // Stub
75: return true;
76: }
77: }
78:
79: class Person {
80: String name;
81: String email;
82: String phone;
83:
84: Person ( String name, String email, String phone ) {
85: this.name = name;
86: this.email = email;
87: this.phone = phone;
88: }
89:
90: // Getters, toString, ...
91: }