I think it's nice to use a Factory Template or an Abstract Factory Template .
The factory pattern returns an instance of several (product hierarchy) subclasses (e.g., FreeCell, TakenCell, etc.), but the calling code is not aware of the actual implementation class.
The calling code calls a method on an interface, such as FreeCell , and the correct doSomething () method is called using polymorphism.
Instead of using instanceof (e.g. switching), you can just call the same method, but each class will implement it according to a local override. This is a very powerful and common feature in many contexts.
Instead, write:
for (Cell cell : cells) { Cell next = cell.futureState(...); if(next instanceof FreeCell) { freeCells.add(currentCell); } ... }
You can enter:
for (Cell cell : cells) { Cell next = cell.futureState(...); cell.doSomething(); // and no matter what class is FreeCell or TakenCell ...
}
Factory pattern returns one of several subclasses. You should use a factory pattern. If you have a superclass and several subclasses, and based on some of the data provided, you should return an object from one of the subclasses.

References:
Abstract Factory Template
Factory pattern
source share