Junior — Middle
What pattern is used to encapsulate the object creation process?
sobes.tech AI
Answer from AI
The "Factory Method" pattern is used to encapsulate the process of object creation. It allows creating objects without specifying the exact classes of the objects being created, delegating this task to subclasses.
Example in Java:
abstract class Creator {
abstract Product factoryMethod();
void someOperation() {
Product product = factoryMethod();
product.doSomething();
}
}
class ConcreteCreator extends Creator {
@Override
Product factoryMethod() {
return new ConcreteProduct();
}
}
interface Product {
void doSomething();
}
class ConcreteProduct implements Product {
public void doSomething() {
System.out.println("Product work");
}
}
This approach simplifies code extension and maintenance.