I am writing another Tetris, just for myself. After Martin and McConel, you want a simple and beautiful architecture. Until a certain moment everything was possible, but crutches began to creep out.
There is the following simplified piece of architecture:
The figure on the field:
class Figure{ List<Shape> shapes; Shape currentShape; }Shape shape:
class Shape{ private int[][] model; }
We need a class that creates different shapes ("T", "J", "L" and others). So far, the fantasy only lasted for this:
public class FigureFactory { private static List< Figure > figures = init(); private static List< Figure > init() { ArrayList< Figure > figures = new ArrayList<>(); Figure J = null, L = null, O = null, S = null, T = null, Z = null; J = new Figure( new Position( 0, 0 ), new ArrayList< Figure.Shape >() {{ add( new Figure.Shape( new int[][]{ { 0, 1 }, { 0, 1 }, { 1, 1 } } ) ); add( new Figure.Shape( new int[][]{ { 1, 0, 0 }, { 1, 1, 1 }, } ) ); add( new Figure.Shape( new int[][]{ { 1, 1 }, { 1, 0 }, { 1, 0 } } ) ); add( new Figure.Shape( new int[][]{ { 1, 1, 1 }, { 0, 0, 1 }, } ) ); }} ); ... return Arrays.asList( J, L, O, S, T, Z ); } public static Figure getJ() { return figures.get( 0 ); } public static Figure getL() { return figures.get( 1 ); } ... public static Figure getRandomFigure() { return figures.get( ( (int) ( Math.random() * figures.size() ) ) ); } Problems and questions are as follows:
Class name The
Factorysuffix, as Google suggests, is used when using the “Abstract Factory” pattern, but here it is clearly not there. What is the best fit?Builderdoes not fit for the same reason. Is there any other pattern for this?Immunity. The main problem -
Figurenot immutable (immutable), because you need to switch the current state (Shape), turning the figure. Now each subsequent call togetL()returns a reference to the same object, changing which will spoil it for subsequent calls. You can move the creation of each specific shape frominit()togetL()/getlJ()and return new objects, but when to be withgetRandomFigure()? We need a method that returns any random shape of all possible, but without a list of possible, it is not clear how to do this. I would like without reflection. The question is not how to make it work, but how to make it nice and neat.Is it reasonable to apply inheritance here by implementing a group of classes like
JFigure,TFigure,LFigureand hiding the whole creation there?
I would be grateful for any links \ books and especially for criticism.