Search code examples
javadesign-patternsdesign-principles

Singleton Polymorphism


Let's assume that i have singleton respresentation of chess board consist of double dimnesion array of cells. Sometimes I want that representation to be consider as board of rows, sometimes as colmumns, sometimes as grids, but every of this case must work on the same underlying singleton of board

So i have 4 class to implement:

class CheesBoard : singleton consist of just a stright dd array of cells
class CheesBoardAsGrids : consist of that same cells but presented by grids
class CheesBoardAsRows : strigtforward as above but rows
class CheesBoardAsColumns : ... you already get it

And i dont know what kind of relationship should be between them to make it the most readable and reusable

for example: i can't inherit from CheesBoard beacuse it's singleton


Solution

  • A singleton, by definition, is an object you want to be instantiated no more than once.

    You can create abstract class Board. The classes CheesBoardAsGrids, CheesBoardAsRows and CheesBoardAsColumns will inherited from this class. The CheesBoard class should contain Board variable.

    If you want your singleton to be initialized with some data, you may load it with data after getInstance method.

    The CheesBoard class should contain init method. This method will get Board parameter and initialize the Board variable:

    Board board = new CheesBoardAsGrids();
    CheesBoard singleton = CheesBoard.getInstance();
    singleton.init(board);