Question

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

Was it helpful?

Solution

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top