Merge pull request #6451 from kwoyke/BAEL-2755

BAEL-2755 - Introduction to the Null Object Pattern
This commit is contained in:
Eric Martin 2019-03-06 21:23:31 -06:00 committed by GitHub
commit b34cdbf4e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 114 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class JmsRouter implements Router {
@Override
public void route(Message msg) {
System.out.println("Routing to a JMS queue. Msg: " + msg);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.nullobject;
public class Message {
private String body;
private String priority;
public Message(String body, String priority) {
this.body = body;
this.priority = priority;
}
public String getPriority() {
return priority;
}
@Override
public String toString() {
return "{body='" + body + '\'' +
", priority='" + priority + '\'' +
'}';
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class NullRouter implements Router {
@Override
public void route(Message msg) {
// do nothing
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.nullobject;
public interface Router {
void route(Message msg);
}

View File

@ -0,0 +1,23 @@
package com.baeldung.nullobject;
public class RouterFactory {
public static Router getRouterForMessage(Message msg) {
if (msg.getPriority() == null) {
return new NullRouter();
}
switch (msg.getPriority()) {
case "high":
return new SmsRouter();
case "medium":
return new JmsRouter();
default:
return new NullRouter();
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.nullobject;
import java.util.Arrays;
import java.util.List;
public class RoutingHandler {
public void handle(Iterable<Message> messages){
for (Message msg : messages) {
Router router = RouterFactory.getRouterForMessage(msg);
router.route(msg);
}
}
public static void main(String[] args) {
Message highPriorityMsg = new Message("Alert!", "high");
Message mediumPriorityMsg = new Message("Warning!", "medium");
Message lowPriorityMsg = new Message("Take a look!", "low");
Message nullPriorityMsg = new Message("Take a look!", null);
List<Message> messages = Arrays.asList(highPriorityMsg,
mediumPriorityMsg,
lowPriorityMsg,
nullPriorityMsg);
RoutingHandler routingHandler = new RoutingHandler();
routingHandler.handle(messages);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.nullobject;
public class SmsRouter implements Router {
@Override
public void route(Message msg) {
System.out.println("Routing to a SMS gateway. Msg: " + msg);
}
}