Design Pattern in Java 101 - Visitor Pattern (Behavioral Pattern)
By admin on Dec 28, 2007 in Behavioral, Java, Programming
NOTE: This is written for me to recap and relearn what I learnt before….
This article is written in order for me to recap what I have learnt and used before, though I know there are already many sites which talked about all these.
Visitor Pattern defines a new operation to deal with the classes of the elements without changing their structures.
E.g.,
Create a IProcess interface,
public interface IProcessor {
public void process(IMessage message);
}
IProcessor accepts IMessage as the parameter.
Create a IMessage interface,
public interface IMessage {
public String parse();
}
Create a MessageProcessor class which implements IProcessor
public class MessageProcessor implements IProcessor{
private String messageType;
public void process(IMessage message) {
messageType = message.parse();
}
public String toString() {
return "Processor for " + messageType ;
}
}
Create SMSMessage and MMSMessage class which implement IMessage
public class SMSMessage implements IMessage {
public String parse() {
return "SMS Message";
}
}
public class MMSMessage implements IMessage {
public String parse() {
return "MMS Message";
}
}
You can create another message processor depending on your need.
public class AnotherMessageProcessor {
private String messageType;
public void process(IMessage message) {
messageType = message.parse();
}
public String toString() {
return "Another Processor for " + messageType;
}
}
To test it, use the following code stub
public class TestPattern {
public static void main(String[] args) {
MMSMessage mmsMessage = new MMSMessage();
SMSMessage smsMessage = new SMSMessage();
MessageProcessor messageProcessor = new MessageProcessor();
AnotherMessageProcessor
anotherMessageProcessor =
new AnotherMessageProcessor();
messageProcessor.process(mmsMessage);
System.out.println(messageProcessor.toString());
messageProcessor.process(smsMessage);
System.out.println(messageProcessor.toString());
anotherMessageProcessor.process(mmsMessage);
System.out.println(anotherMessageProcessor.toString());
anotherMessageProcessor.process(smsMessage);
System.out.println(anotherMessageProcessor.toString());
}
}
The output
Processor for MMS Message Processor for SMS Message Another Processor for MMS Message Another Processor for SMS Message

Erin Klein | Apr 19, 2008 | Reply
papacy accoladed blaff unmoving damagement bescent aboriginal selfsameness
Diesel Spares India
http://www.whisperingspiritsartgallery.com/