我目前处于此问题的设计模式:
实施预定义的扬声器界面。创建三个以各种方式实现Speaker的类。创建一个驱动程序类,其主方法实例化其中一些对象并测试它们的能力。
我将如何设计此程序并进入编码阶段。我想使用这三个类来实现Speaker接口类:Politician,Lecturer和Pastor类。我想要使用的方法是:
public void speak();
public void announce (String str);
现在我的设计和编码,我将如何声明和对象引用变量并让该变量有多个引用?
答案 0 :(得分: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.
答案 1 :(得分: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...
}
答案 2 :(得分:-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();
....
}
}
}