假设我有一个CommonClass
类,它显示所有其他类文件的共同点:
public class CommonClass {
public static void displayFoo() {
... // printlns here
displaySpecific(); // Among all files made common by this method, I
// want to display something different among the other files
... // printlns here
}
}
我打算这样称呼:
// Filename: fileA.java
public class FileA {
public static void myFunc() {
CommonClass.displayFoo();
// however, I should have a specific definition
// for the displaySpecific()
// method. Should I use interfaces? How should it be structured.
}
// displaySpecific method here
}
另一个档案:
// Filename: fileB.java
public class FileB {
public static void myFunc() {
CommonClass.displayFoo();
// however, I should have a specific definition
// for the displaySpecific()
// method. Should I use interfaces? How should it be structured.
}
// displaySpecific method here
}
依旧......
主要可能是......
public class MyMain {
public static void main(String[] args) {
FilaA.myfunc();
System.out.println("");
FileB.myfunc();
System.out.println("");
... and so on...
}
}
这是预期的输出:
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
This is File A
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
This is File B
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
我该怎么做?
答案 0 :(得分:1)
如果每个类需要不同的displayFoo()
定义,那么它们应该是类函数。您对界面的想法可能就是您想要的方式。
public class FileB implements Displayable {
public static display() {
// Implementation-specific display
// etc.
然后,您只需在可显示的对象上调用display()
:
for (Displayable d : displayables) {
d.display();
}
但是,在您的示例中,您并不真正需要界面或其他任何内容,因为您正在调用myfunc()
,而display()
会调用该类自己的public class DisplayUtil {
public static void display(FileA f) {
// etc.
}
public static void display(FileB f) {
// etc.
}
}
。
你可以创建这样的东西:
java.lang.String
不是模式的忠实粉丝,但是如果你没有访问原始资源,或者他们是最后的课程(我在看你,{{1}}),它可能是更方便的选择。