📄 visitor.java
字号:
package Jt.examples.patterns;
import java.beans.*;
import java.lang.reflect.Method;
import Jt.*;
import Jt.examples.HelloWorld;
/**
* Demonstrates the use of the Visitor pattern.
*/
public class Visitor extends JtObject {
public static final String JtCLASS_NAME = Visitor.class.getName();
private static final long serialVersionUID = 1L;
public Visitor() {
}
// Print the object attributes. This is the new functionality.
private void printObject (Object obj) {
PropertyDescriptor[] prop;
int i;
Method m;
BeanInfo info = null;
Object value;
if (obj == null)
return;
try {
info = Introspector.getBeanInfo(
obj.getClass (), obj.getClass ().getSuperclass());
} catch(Exception e) {
handleException (e);
return;
}
prop = info.getPropertyDescriptors();
for(i = 0; i < prop.length; i++) {
try {
m = prop[i].getReadMethod ();
if (m == null) {
handleError
("getReadMethod returned null");
return;
}
value = m.invoke (obj, null);
if (value != null)
System.out.print (obj.getClass ().getName () + "." +
prop[i].getName() + ":" + value);
} catch (Exception e) {
handleException(e);
return;
}
}
}
/**
* Process object messages.
* <ul>
* <li>JtVISIT - visit the object specified by msgContent.
* </ul>
* @param event Jt Message
*/
public Object processMessage (Object event) {
String msgid = null;
JtMessage e = (JtMessage) event;
Object content;
if (e == null)
return null;
msgid = (String) e.getMsgId ();
if (msgid == null)
return null;
content = e.getMsgContent();
if (msgid.equals (JtObject.JtREMOVE)) {
return (null);
}
if (msgid.equals (JtObject.JtVISIT)) {
printObject (content);
return (null);
}
return (super.processMessage(event));
}
/**
* Test program
*/
public static void main(String[] args) {
JtObject main = new JtFactory ();
JtMessage msg;
Visitor visitor;
JtInterface node;
// Create an instance of JtVisitor
visitor = (Visitor)
main.createObject (Visitor.JtCLASS_NAME, "visitor");
node = (JtInterface) main.createObject (HelloWorld.JtCLASS_NAME, "helloWorld");
((HelloWorld)node).setGreetingMessage("my hello message");
System.out.println ("This visitor prints the object using a custom format ...\n");
// Send an JtACCEPT message to the node. The message contains
// a reference to the visitor
msg = new JtMessage (JtObject.JtACCEPT);
msg.setMsgContent (visitor);
main.sendMessage (node, msg);
// Remove objects
main.removeObject (visitor);
main.removeObject (node);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -