This is more of a "best practice" or "best approach" kind of question; I was able to solve the core Problem myself, but I wonder how a situation like this should best be resolved.
Imagine a 2-dimensional board with a grid of square cells. Each cell is an independent instance of a class.
This would be the Pseudocode:
class Board {
int width;
int height;
Array cells;
}
class Cell {
Board parent;
int x;
int y;
int value;
}
(To make the example a bit more clear: Imagine this is a Sudoku puzzle, with each cell holding a value.)
Now, while each Cell
is independent, some Cells
share a border. Let's say that this border is also it's own class, since it can be configured separately (for example, one cell's top border might be of a different color, style or thickness).
Now, if I extend the Pseudocode to accomodate for this:
class Cell {
...
Array borders;
}
class CellBorder {
Cell parent;
int direction; // 0=top, 1=right, 2=bottom, 3=left
Style style; // thickness, style, color, etc.
}
My Question is: Clearly, two connected Cells
share a Border
- what's the best way to deal with something like this?
- Where is the
Border
instance initially created? Inside theCell
? Outside theCell
, in theBoard
class? - How would two
Cells
share aBorder
? Do they each have a pointer to the same instance, or two separate instances that just copy each other? - What if a
Cell
is moved to a different position? Are all affectedBorders
reconstructed or existing instances swapped? - If I want to configure a specific Border, how do I select it? By picking
Cell(x,y).rightBorder
?Cell(x+1,y).leftBorder
?Board.border(x,y,'right')
? (Ideally it shouldn't matter, but perhaps there is some benefit to one method over the other) - Should
Borders
(and perhaps evenCells
) be created in a factory?
My current solution, is to only have the "top" and "left" Borders
in each Cell
, while linking the "bottom" and "right" Border
to the neighbors "top" and "left" Borders
respectively.
But generally speaking, what would be a good and flexible approach here? Would the Border
handling be relayed to the Board
instead of the Cells
? I'm sure this type of problem must be fairly common and has some best-practices or perhaps even a well-suited design pattern.
Aucun commentaire:
Enregistrer un commentaire