How does the use of the factory pattern differ from the implementation of a factory in Java?
sobes.tech AI
Answer from AI
The "Factory Method" pattern is a design pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate. It is used to delegate the creation of objects to subclasses, providing flexibility and extensibility.
The implementation of a factory in Java can be either a concrete class with methods for creating objects (for example, a Factory class with a createProduct() method) or using the factory method pattern. The main difference is that the factory method is specifically a pattern with a defined structure (interface or abstract class with a factory method), whereas a "factory" in Java can simply be a utility class for creating objects without strictly following the pattern.
Example of a factory method:
abstract class Creator {
abstract Product factoryMethod();
void someOperation() {
Product product = factoryMethod();
// work with the product
}
}
class ConcreteCreator extends Creator {
@Override
Product factoryMethod() {
return new ConcreteProduct();
}
}
Example of a simple factory:
class SimpleFactory {
static Product createProduct(String type) {
switch(type) {
case "A": return new ProductA();
case "B": return new ProductB();
default: throw new IllegalArgumentException("Unknown type");
}
}
}
Thus, the factory method is a pattern with inheritance and method overriding for creation, while a factory is a more general term that can be implemented in various ways.