Java 如何保护要直接实例化的类
如何更改此实现:Java 如何保护要直接实例化的类,java,uml,Java,Uml,如何更改此实现: public interface Animal() { public void eat(); } public class Dog implements Animal { public void eat() {} } public void main() { // Animal can be instantiated like this: Animal dog = new Dog(); // But I dont want the user
public interface Animal()
{
public void eat();
}
public class Dog implements Animal
{
public void eat()
{}
}
public void main()
{
// Animal can be instantiated like this:
Animal dog = new Dog();
// But I dont want the user to create an instance like this, how can I prevent this declaration?
Dog anotherDog = new Dog();
}
创建工厂方法并保护构造函数:
public class Dog implements Animal {
protected Dog () {
}
public static Animal createAsAnimal () {
new Dog ();
}
}
通过创建factory方法,可以按如下方式执行:
public interface Animal {
public void eat();
public class Factory {
public static Animal getAnimal() {
return new Dog();
}
private static class Dog implements Animal {
public void eat() {
System.out.println("eats");
}
}
}
}
Dog类对用户不可见。
要运行:
您可能希望使构造函数
私有化,以禁止子类化。您是对的@Alexander Pogrebnyak,我们仍然可以保持对象类型为Dog,不是吗?!!!例如:另一只狗=…@Natix。OP没有说明是否应将Dog
子类化。我假设它可能是,因为OP没有在示例中声明它final
。在final
Dog
类的情况下,我会非常明确地声明构造函数private
@AlexanderPogrebnyak,如果您允许对Dog进行子类化,例如类Hound extensed Dog{}
,那么客户端可以调用Dog Dog=new Hound()代码>但如果我再想想,原来的问题在当前形式下没有多大意义。更正从implements Animal()移除(){即将implements Animal()更改为implements Animal(){it to implements Animal(){
Animal dog= Animal.Factory.getAnimal();
dog.eat();//eats