【问题标题】:Abstract static factory method [getInstance()] in Java?Java中的抽象静态工厂方法[getInstance()]?
【发布时间】:2011-03-17 03:02:53
【问题描述】:

当然,以下在 Java 中不起作用(没有抽象静态方法)...

public abstract class Animal {
    public abstract static Animal getInstance(byte[] b);
}

public class Dog extends Animal {
    @Override
    public static Dog getInstance(byte[] b) {
        // Woof.
        return new Dog(...);
    }
}

public class Cat extends Animal {
    @Override
    public static Cat getInstance(byte[] b) {
        // Meow.
        return new Cat(...);
    }
}

要求Animal 类具有实例化自身的静态getInstance 方法的正确方法是什么?这个方法应该是静态的; “正常”的抽象方法在这里没有意义。

【问题讨论】:

标签: java abstract-class factory static-methods


【解决方案1】:

无法在抽象类(或接口)中指定实现类必须具有特定的静态方法。

使用反射可以获得类似的效果。

另一种方法是定义一个与Animal 类分开的AnimalFactory 接口:

public interface AnimalFactory {
    Animal getInstance(byte[] b);
}

public class DogFactory implements AnimalFactory {
    public Dog getInstance(byte[] b) {
        return new Dog(...);
    }
}

public interface Animal {
    // ...
}

class Dog implements Animal {
    // ...
}

【讨论】:

  • 从现有实例中请求新实例是没有任何意义的,因为如果还存在零个实例,您将无法获得一个。这就是经典的静态工厂方法的用武之地(我理解很难实现好的设计,因为你不能提供静态接口或抽象方法)。
猜你喜欢
  • 1970-01-01
  • 2010-09-23
  • 2012-12-03
  • 2011-01-05
  • 2014-01-14
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多