Pregunta

Let's say one Java program that does not have abstract methods, is it possible to implement the Factory Method pattern without abstract methods?

¿Fue útil?

Solución

Absolutely: a factory method does not need to be an abstract one - it could be a non-abstract method with a default implementation throwing an exception, or it could be a method of an interface, which is always abstract.

interface Product {
    void doSomething();
}
interface Creator {
     Product create(String someData);
}
class ProductX implements Product {
    public void doSomething() {
         System.out.println("X");
    }
}
class ProductY implements Product {
    public void doSomething() {
         System.out.println("y");
    }
}
class XYFactory implements Creator {
    public Product create(String someData) {
        if ("X".equals(someData)) {
            return new ProductX();
        }
        if ("Y".equals(someData)) {
            return new ProductY();
        }
        return null;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top