【问题标题】:How would I go about implementing this Java interface?我将如何实现这个 Java 接口?
【发布时间】:2012-11-12 21:55:31
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 只是猜测:implements Speaker
  • 你看过关于如何使用接口的教程吗?这一切都会在那里解释。我们不太擅长重写这些教程,但是一旦你尝试过,我们更擅长帮助你解决错误——我强烈建议你这样做。
  • (提示:将接口实现为类似于父类的子类化。)
  • 声明一个对象引用变量怎么样?有示例代码吗?

标签: java interface implementation implements interface-implementation


【解决方案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();

          ....

          }
      }

}

【讨论】:

    【解决方案2】:

    请参阅“什么是接口?” 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...
    }
    

    【讨论】:

      【解决方案3】:

      真的很简单。简而言之:

      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.
      

      【讨论】:

      • 那么对于我的 3 个演讲者课程,我将如何让每个课程更具体但仍使用 speak() 和announce() 方法。
      • 当您的扬声器类实现一个接口时,它们必须提供一个实现。在 ClassA 的示例中,我是说 ClassA 会通过打印出“我爱 Java”来说话..
      • 另外,如果您注意到我创建扬声器数组的方式,而不是 A/B/C 类数组。
      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      相关资源
      最近更新 更多