面向对象系统通实现了多个对象之间的消息传递和互动,形成了对象活动的自动化,看了一个帖子,感觉有意思,重新实现了一下:强盗抢劫居民,居民自动报警,警察局自动派出警察,警察抓捕强盗
package com.foo;
public class FooMain {
public static void main(String[] args) {
PoliceStation ps = new PoliceStation("上海市警察局");
ps.hire(new Police("雷锋"));
Resident r = new Resident("张三");
r.regist(ps);
Robber ro = new Robber("李四");
ro.ro.robbing(r);
}
}
/*
result:
张三 在 上海市警察局 辖区居住
强盗 李四 抢劫 张三
居民 张三 报警!
上海市警察局 接到 张三 报警
上海市警察局 派出警察 雷锋
警察 雷锋 抓捕强盗 李四
*/
/
package com.foo;
public class Resident {
private String name;
PoliceStation ps;
public Resident(String name){
this.name = name;
}
public void regist(PoliceStation ps){
System.out.println(this.getName()+" 在 "+ps.getName()+" 辖区居住" );
this.ps = ps;
}
public void call110(Iillegaler il){
System.out.println("居民 "+name+" 报警!");
ps.accept(this,il);
}
public void attackedBy(Robber t){
call110(t);
}
public String getName() {
return name;
}
}
}
///
package com.foo;
public interface IRobber extends Iillegaler {
public void robbing(Resident r);
}
/
package com.foo;
public interface Iillegaler {
}
/
package com.foo;
public class Robber extends Resident implements IRobber {
public Robber (String name){
super(name);
}
@Override
public void robbing(Resident r) {
System.out.println("强盗 "+this.getName()+" 抢劫 " +r.getName());
r.attackedBy(this);
}
}
///
package com.foo;
public class Police extends Resident {
public Police(String name){
super(name);
}
public void arrest(Iillegaler il) {
if (il instanceof Robber)
System.out.println("警察 "+this.getName()+" 抓捕强盗 " +((Robber)il).getName());
// ....
}
}
//
package com.foo;
public class PoliceStation {
Police p;
String name;
Iillegaler il;
public PoliceStation(String name){
this.name = name;
}
public String getName() {
return name;
}
public void hire(Police p){
this.p = p;
}
private void send(){
System.out.println(name+ " 派出警察 "+p.getName());
p.arrest(il);
}
public void accept(Resident resident, Iillegaler il) {
System.out.println(name+" 接到 "+resident.getName()+" 报警");
this.il = il;
this.send();
}
}