好吧,我想用一个我基本上想做的例子来开始我的问题,尽管它不是这样工作的。
我想要一个接口(interface) IDog
强制其实现具有一些方法。我还想要一个父类(super class) AbstractDog implements IDog
来为所有 Dog
类提供基本属性和方法。然后我想要像 Poodle extends AbstractDog
这样的子类。我的问题是 static
方法 - 我基本上希望 AbstractDog
的每个子类都有不同的 static
方法,但我希望能够强制执行此操作来自 IDog
的方法。
所以我天真的(也是错误的)实现是:
public interface IDog {
String getName(); // every dog instance should be able to call name
static String getDescription(); // every dog class should be able to get its description
}
public abstract class AbstractDog implements IDog {
private String name; // every dog instance will have this
public AbstractDog(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name; // every dog instance can call this
}
}
public class Poodle extends AbstractDog {
private static String description = "It's a poodle!"; // all Poodles have the same description
public Poodle(String name) {
super(name);
}
@Override // from IDog
public static String getDescription() {
return description;
}
}
现在,正如我所说,这是不正确的,因为 AbstractDog
类需要一个 static abstract
方法 getDescription()
和 IDog
需要其方法的实现并且不能被覆盖。
我想知道,是否有一种设计模式符合我的问题:强制执行一组类(可以或应该有一个中间父类(super class))来实现一个(不同的!)静态方法。
我发现了一种可能性,但我不确定它是否有用或什至是否足够,是使用 enum DogType
然后只使用 class Dog
具有 DogType
属性:
public enum DogType {
Poodle("This is a poodle."), Havanese("This is a Havanese.)";
private String description;
private DogType(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
public class Dog {
private String name;
private DogType dogType;
public Dog(String name, DogType dogType) {
this.name = name;
this.dogType = dogType;
}
public String getName() {
return this.name;
}
public String getDescription {
return this.dogType.getDescription();
}
}
但是,这种“解决方法”失去了我最初想法的能力:我现在不能只为一个狗类添加功能,比如实例方法 void prance()
应该只能访问 Poodle
。
关于类似问题的许多主题都提到了工厂模式,但我不确定它如何适合我的问题,因为我不一定需要构造方法。随着赛狗数量的增加,我认为我的代码会变得非常困惑。或者,也许我只是不明白在我的案例中应该如何正确使用工厂。
最佳答案
接口(interface)是强制行为。类用于指定属性。静态方法被隐藏。它们不会被子类覆盖。因此,如果您的子类中有静态方法,但您的对象引用是父类(super class)型类,那么将调用父类(super class)中的静态方法。这是类方法隐藏,发生在静态方法中。
I want to know, if there is a Design pattern which matches my problem: enforcing a set of classes (which could or should have an intermediate superclass) to implement a (different!) static method.
对不起。静态方法和继承不能齐头并进。
I now can't additional functionalities to only one dog class like an instance method void prance() which should only be accessible to Poodle.
您可以使用方法 void prance()
引入接口(interface) Pranceble
。
public interface Prancable{
void prance();
}
public class Poodle extends Dog implements Prancable{
@Override
public void prance(){
System.out.println("My Poodle can prance.");
}
}
您可以按照这种方式处理为不同犬种添加行为的特定方法。
关于java - 强制执行静态方法所需的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38811895/