猫,老鼠什么的

来源:互联网 发布:刘嘉忆 知乎 编辑:程序博客网 时间:2024/04/23 23:12

 

 

public static void main(String[] args){
       
    TestEnv env = new TestEnv(new Tom(), new Jerry(), new Jerry(), new Adm());
    env.sound(Tom.cry);
}
       

class TestEnv{
    Animal[] animals;
    public TestEnv(Animal ... animals){
        this.animals = animals;
    }
   
    public void sound(Sound x){
        for(Animal a : animals){
            a.listen(x);
        }
    }
}

class Sound {
    //equals
}



interface Action{
    public void doAction(Object o);
}


abstract class Animal{
    public Map actions = new HashMap();
   
    public void listen(Sound x){
        Action action = (Action) actions.get(x);
        if(action!=null){
            action.doAction(x);
        }
    }
}

class Jerry extends Animal{
   
    public Jerry(){
        actions.put(Tom.cry, new RunAway());
    }
   
    class RunAway implements Action{
        public void doAction(Object o) {
            System.out.println("I should run away!");
        }
    }
}

class Tom extends Animal{
    public static final Sound cry = new Sound();
   
}


class Adm extends Animal{
   
    public Adm(){
        actions.put(Tom.cry, wakeup);
    }
   
    static Action wakeup = new Action(){
        public void doAction(Object o) {
            System.out.println("Shut up, xxxxx cat!");
        }
    };
   
}