编程的一个重要思想是:面向接口编程,而不是面向对象编程。作为类的使用者,无需知道他使用的类的特定对象类型,只需要对象拥有特定的接口。例如,canFlight可以有很多实现类,有Hero,也可以有Bird等。但是你在编程中不需要关心到底是什么,只需要使用canFlight的方法即可。

解决方案 »

  1.   

    the rule is:
    "ask only what you need. Promise only necessary."
    in your method t, what you need is really just a CanFight, you should not ask for Hero.
    What if I have a HuaiDan class which also implements CanFight? 
    if you change it to Hero, my HuaiDan can not be used.Of course, if what you want is just Hero, no HuaiDan is allowed, then Hero is ok.
    It really depends on what the requirement is.
      

  2.   

    这个可是设计模式的问题了,如果你硬要这么做的话,那又何必要那么多的接口呢!?还不如把这些方法都写到HERO的父类中去呢!你说是吧!
    这样写的好处,只是加强了代码结构的清晰,具体的接口具有具体的功能,这样的代码维护起来多好呀!你说是吧!?
      

  3.   

    ok. as I said, it really depends on your requirement. If you just WANT to restrict it to Hero, nobody can force you.
    But, normally, you don't care what is the actual implementation class, all you want is an object that can do certain operations.
    So, I'm assuming that in your t function, what you want is "something that can fight", then you make it fight.
    so, if you write your t function as t(Hero h); It also works for Heros.But now I have a class 
    class HuaiDan implements Fightable
    {
        public void fight(){......}
    }how can I use your t function to make my HuaiDan fight?
    Do I need to copy your t function and change the Hero to HuaiDan?Even so, what if later we have a SomewhatHuaiDan implements Fightable?
      

  4.   

    don't talk about design pattern. It's only making things complex.
    just remember, "don't ask for more than you need". if you ask for more, other module would be harder to give it to you.In your case, what you need is "anything that can fight". not "a hero".
      

  5.   

    这只是一个设计模式提高代码可重用性的问题!!!原来的代码可重用性好!!!!!
    就对以本例来说。似乎是你的那种方式好一点,更清晰!但是,这样的话就降低了代码的可重用性了,丢失了部分多太性!
    (Hero与各个接口间的多太性丢了!)打个比方,我假如新增加了各类如下:
    class Hero2 extends  CanSwim, CanFly {
      public void swim()  {System.out.println("swim()");}
      public void fly()   {System.out.println("fly()");}
    }
    明显就不能重用你的代码了!而THINK IN JAVA 代码中的
      static void u(CanSwim x) 
      static void v(CanFly x) 
    且照用无误!
    通常在设计函数的参数时中要遵守尽量采用基类,或基接口,越底层越好的原则,
    这样的话代码可重用性相对来说肯定要好一点!以上是个人看法!满意的话给分!:-)
      

  6.   

    你这样理解吧,其实这样设计的好处就是可以根据不同的对象实现不同的METHOD!
    比如说CanSwim, CanFly 这两个接口中的方法public void swim(),public void fly()在hero这个类中的实现是System.out.println("swiming")和System.out.println("flying");但有可能在bird中的实现是其它的代码(不是简单的打印)这个时候你的接口就起到了作用,它隐藏了具体类的信息,加强了封装性.不过话说回来了,如果你只是要建立一个hero class,那有何必用接口呢!?直接在类中写method不就可以了嘛!?所以我建议你还是按你的需求来写代码,比如等到你需要很多类都需要实现canfly(),camSWIM()等方法的时候,再将你的程序接口化!