Skip to content

Instantly share code, notes, and snippets.

@cozos
Last active July 6, 2016 03:36
Show Gist options
  • Save cozos/007c5183448c1c22187dd5eabe7c205d to your computer and use it in GitHub Desktop.
Save cozos/007c5183448c1c22187dd5eabe7c205d to your computer and use it in GitHub Desktop.
TextDisplay *textDisplay = new TextDisplay();
Grid *grid = new Grid(n, n);
// Create a cell for every single slot.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid->setCell(i, j, new Cell());
}
}
// Set observers for every single cell.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Cell *currentCell = grid->getCell(i, j);
Cell [] adjacentCells = grid->getAdjacentCells(i, j);
// if i=2 and j=2, then getAdjacentCells would return
// grid.getCell(1,2), grid.getCell(2, 1), grid.getCell(3, 2), and grid.getCell(2, 3)
for (Grid *adjacentCell : adjacentCells) { // This syntax probably doesn't exist in C++03 or whatever you use but you get my point
currentCell->addObserver(adjacentCell);
}
currentCell->addObserver(textDisplay);
// And then, for example, you do this:
currentCell->notifyAllObservers("I was clicked")
}
}
@cozos
Copy link
Author

cozos commented Jul 6, 2016

public void Cell::notifyAllObservers(String event) {
    for (Observer *observer : this.observers) {
        observer->notify(event);
    }
}

public void Cell::notify(String event) {
    if (event == "I was clicked") {
        this.onStatus = !this.onStatus;
        this.notifyAllObservers("I switched status");
    }
}

public void TextDisplay::notify(String event) {
    if (event == "I switched status") {
        this.redraw();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment