如何保护类直接实例化

时间:2013-02-01 00:09:56

标签: 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();
}

2 个答案:

答案 0 :(得分:7)

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

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

   public static Animal createAsAnimal () {
      new Dog ();
   }
}

答案 1 :(得分:1)

您可以通过创建工厂方法来执行以下操作:

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类。 要运行:

Animal dog= Animal.Factory.getAnimal();
dog.eat();//eats