面向对象设计的小例子

面向对象系统通实现了多个对象之间的消息传递和互动,形成了对象活动的自动化,看了一个帖子,感觉有意思,重新实现了一下:强盗抢劫居民,居民自动报警,警察局自动派出警察,警察抓捕强盗
类图


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();    
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值