mic*_*con 8 java inheritance singleton code-formatting
我有一组单例类,我想避免样板代码.这就是我现在拥有的:
public class Mammal {
protected Mammal() {}
}
public class Cat extends Mammal {
static protected Cat instance = null;
static public Cat getInstance() {
if (null == instance) {
instance = new Cat();
}
return instance;
}
private Cat() {
// something cat-specific
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,并没有任何问题,除了我有许多Mammal必须复制getInstance()方法的子类.如果可能的话,我更喜欢这样的东西:
public class Mammal {
protected Mammal() {}
static protected Mammal instance = null;
static public Mammal getInstance() {
if (null == instance) {
instance = new Mammal();
}
return instance;
}
}
public class Cat extends Mammal {
private Cat() {
// something cat-specific
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么做?
你不能,因为构造函数既不是继承的也不是可重写的。在您想要的示例new Mammal()中,仅创建 a Mammal,而不是其子类之一。我建议你看看 Factory 模式,或者使用 Spring 之类的模式,它就是专门针对这种情况的。
| 归档时间: |
|
| 查看次数: |
3662 次 |
| 最近记录: |