2011年(6)
分类: Java
2011-05-04 20:28:17
下面的例子中我们不在setup()中打印信息,而是把它放在一个简单行为中:
在jadetest包里面新建一个java类命名为SimpleBehaviour,输入下面代码。
package jadetest;
import jade.core.*;
import jade.core.behaviours.Behaviour;
public class SimpleBehaviour extends Agent {
public void setup(){
Behaviour hello_behaviour = new Behaviour(this){
boolean finished = false;
// 覆盖 Behaviour 类的action这一抽象方法
public void action(){
System.out.println("Hello World Behaviour run: Hello World!");
System.out.println("-----About Me:-----");
System.out.println("My local name is:"+getLocalName());
System.out.println("My globally unique name is:"+getName() );
System.out.println("-----About Here:-----");
Location l = here();
System.out.println("I am running in a location called:"+l.getName());
System.out.println("Which is identified uniquely as:"+l.getID());
System.out.println("And is contactable at:"+l.getAddress());
System.out.println("Using the protocol:"+l.getProtocol());
finished = true; }
// done()在父类中也是一个抽象方法
public boolean done(){
return finished;}
};
addBehaviour(hello_behaviour); } //setup()
}// java jade.Boot helloBehaviours:HelloWorldBehaviours
要想使得eclipse中的项目能在不同类之间交换执行(即执行完HelloWorld之后再测试SimpleBehaviour)就得把Agent项目属性中的启动参数改为“-gui sb:jadetest.SimpleBehaviour”.
输出结果为:
Hello World Behaviour run: Hello World!
-----About Me:-----
My local name is:sb
My globally unique name is:sb@180.85.181.143:1099/JADE
-----About Here:-----
I am running in a location called:Main-Container
Which is identified uniquely as:Main-Container@180.85.181.143
And is contactable at:180.85.181.143
Using the protocol:jicp
这个程序相较于前面的例子多了action, done两个函数,它们分别执行自己的操作。HelloWorldBehaviours类加载时定义一个简单行为,这个简单行为执行的操作由action,done来实现。然后,再通过加载语句(addBehaviour(hello_behaviour))执行这个简单行为。