如何保护类直接实例化

oli*_*dev 3 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 to create an instance like this, how can I prevent this declaration?
  Dog anotherDog = new Dog();
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*yak 7

创建工厂方法并保护构造函数:

public class Dog implements Animal {
   protected Dog () {
   }

   public static Animal createAsAnimal () {
      new Dog ();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望使构造函数`private`禁止子类化. (2认同)