-4

我目前处于此问题的设计模式:

实现预定义的 Speaker 接口。创建三个以各种方式实现 Speaker 的类。创建一个驱动程序类,其主要方法实例化其中一些对象并测试它们的能力。

我将如何设计这个程序以及他们进入编码阶段。我想用这三个类来实现 Speaker 接口类:Politician、Lecturer 和 Pastor 类。我想使用的方法是:

public void speak(); public void announce (String str);

现在对于我的设计和编码,我将如何声明和对象引用变量并让该变量具有多个引用?

4

3 回答 3

1

真的很简单。简单来说:

class ClassA implements Speaker
{
   public void speak(){
          System.out.println("I love Java") ; //implement the speak method
    }
}
class ClassB implements Speaker //follow the example of ClassA
class ClassC implements Speaker //same as above

Speaker[] speakers = new Speakers{new ClassA(),new ClassB(),new ClassC()} ;

for(Speaker speaker: speakers)
   speaker.speak(); //polymorphically call the speak() method defined in the contract.
于 2012-11-25T02:10:19.023 回答
0

请参阅“什么是接口?” http://docs.oracle.com/javase/tutorial/java/concepts/interface.html 这有望让您开始了解您正在寻找的基础知识。

实施的开始将类似于以下内容......

class Politician implements Speaker
{
  public void speak()
  { 
    // Method implementation
  }
  public void announce (String str)
  {
    // Method implementation
  }
}
class Lecturer implements Speaker
{
  public void speak()
  { 
    // Method implementation
  }
  public void announce (String str)
  {
    // Method implementation
  }
}
class Lecturer implements Speaker
{
  public void speak()
  { 
    // Method implementation
  }
  public void announce (String str)
  {
    // Method implementation
  }
}

public static void main(String [] args)
{
   Speaker s1 = new Politician();
   Speaker s2 = new Pastor();
   Speaker s3 = new Lecturer();
   // Do something...
}
于 2012-11-25T02:11:52.543 回答
-1

使用工厂方法设计模式。在http://en.wikipedia.org/wiki/Factory_method_pattern查看这篇文章

如果您使用工厂模式,您的代码可能看起来像这样

public class SpeakerFactory {

      enum SpeakerEnum { POLITICIAN, LECTURER, PASTOR} ;
      Speaker getSpeaker(SpeakerEnum speakerType) {
          switch (speakerType) {

          case POLITICIAN : return new Politician();

          ....

          }
      }

}

于 2012-11-25T04:05:31.487 回答