2011-03-21 100 views
4

下面编码的多态性是否有区别?基本上,方法调用的绑定有区别吗?使用接口和类的多态性

多态性类型1:

public interface Command 
{ 
    public void execute(); 
} 

public class ReadCommand implements Command 
{ 
    public void execute() 
    { 
     //do reading stuff 
    } 
} 

public class WriteCommand implements Command 
{ 
    public void execute() 
    { 
     //do writing stuff 
    } 
} 

public class CommandFactory 
{ 
    public static Command getCommand(String s) 
    { 
     if(s.equals("Read")) 
     { 
      return new ReadCommand(); 
     } 
     if(s.equals("Write")) 
     { 
      return new WriteCommand(); 
     } 

     return null; 
    } 
} 

现在我使用命令工厂:

class A 
{ 
    public void method() 
    { 
     // do stuff 
    } 
} 

class B extends A 
{ 
    public void method() 
    { 
     // do other stuff 
    } 
} 

现在用的是

A a = new B(); 
a.method(); 

多态性类型2 I做的东西与乙

Command c = CommandFactory.getCommand("Read"); 
c.execute(); 

我的问题是:上述两种多态性是否有区别。我知道这两个都是运行时多态性的例子,但是[关于方法绑定的方面]有什么区别,或者有什么区别?

回答

2

我想有

Command c = CommandFactory.getCommand("Read"); 

A a = new B(); 

之间的一个区别......在第一种情况下,你有别无选择但使用的,因为接口(或只是Object)赋值运算符右侧的表达式为Command

在第二种情况下,你是故意选择的结果分配给A类型的变量,即使你可能已经写

B b = new B(); 

这真的只是在一个差异设计选择 - 它不会影响c.execute()a.execute()的实际行为。

+0

@Swaranga:鉴于这是与谷歌采访有关,我认为我最好不要评论任何进一步说实话... – 2011-03-21 12:26:41

1

Polymorphism Type 1Polymorphism Type 2是一样的多态性:)

0

对于运行行为有没有什么不同。但是

区别在于汇编。即

在1st Type中,当您使用直接类引用时,需要两个类都在编译时出现。

但是对于第二种类型的类只在运行时才需要。

+0

不,第二种类型的'CommandFactory'在编译时需要'ReadCommand'和'WriteCommand',并且最终在运行时需要。 – jmg 2011-03-21 11:02:49

+0

如果您已经分别编译了CommandFactory并将其添加到jar中,该代码在其类路径中具有该jar,那么在编译时不需要它。 – GuruKulki 2011-03-21 11:11:50

0

绑定(运行时)没有区别。类型1是紧密耦合的,而类型2是松散耦合的,在编译时有所不同。