lundi 18 décembre 2017

Is there a python design pattern for a Grid class that can contain different types of Cell classes?

For a python hobby-project I needed a grid that consists of cells, as in:

Grid consisting of cells

For this I created a generic Grid class that contains a list of generic Cell objects. Both have sub-classes, because I need different types of grids, each of which contain different types of cells. Like in this class diagram:

Class diagram

I implemented the generic Grid and Cell classes as follows:

class Cell:
    def __init__(self, row_index, column_index):
        self.row_index = row_index
        self.column_index = column_index

class Grid:
    def __init__(self, size, cell):
       self.cells = [cell(i, j) for i in range(size) for j in range(size)]

In which the cell parameter of the Grid constructor specifies which type of cell to use for building up this grid. A specific sub-class would then look as follows:

class CellS(Cell):
    def __init__(self, row_index, column_index):
        super().__init__(row_index, column_index)
        # other stuff

class GridA(Grid):
    def __init__(self):
        super().__init__(9, CellS)

It works fine, but it feels a bit weird (and it has the downside that the constructor of the Cell sub-classes cannot have additional parameters, but that is not an issue for my case).

Am I overlooking some obvious design pattern for handling such a situation? I did a bit of research, but I could not find any suitable other solution for this.

Aucun commentaire:

Enregistrer un commentaire