Domanda

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

È stato utile?

Soluzione

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;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top