Upcoming SlideShare
×

# Applying design patterns

520 views
392 views

Published on

We solve Sudoku by following certain routines in our mind. Thus we have to apply handful of patterns to solve each of these routines. I am taking just one of these patterns good enough for solving easy ones and delve in to detail.

Published in: Software
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
520
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
6
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Applying design patterns

1. 1. Applying Design Patterns Solving Sudoku, easy ones
2. 2. Problem
3. 3. Design Patterns Problem Pattern Solution
4. 4. Applying Patterns • Break the problem down to common known problems • Apply Known Solutions
5. 5. A Common Problem • When a number is placed in a cell, the adjacent cells loose the opportunity to have this number • How to make the adjacent cell react on placement of a number?
6. 6. A Known Solution • Cells that are adjacent to a cell can be made to observe and react on placement of a number using Observer Pattern
7. 7. Setup • To start with, each cell can have any value between 1 and 9, inclusive, with equal probability. public class Cell { private List values = new ArrayList(); private int row; private int col; // Add all possible entries (1 to 9) in each cell public Cell(int row, int col) { this.row = row; this.col = col; for (int n = 1; n <= 9; n++) { values.add(new Integer(n)); } } }
8. 8. Cell as Observable and Observer public class Cell extends Observable implements Observer { //… public synchronized void addObserver(Cell[][] cells) { //… loop thru and add adjacent cells as observers super.addObserver(cells[i][j]); //… } //notify observers while setting the known value in the cell public void setValue(int value) { super.notifyObservers(new Integer(value)); } // Observe and remove the entry set in the observable public void update(Observable o, Object arg) { values.remove(arg); } } • Observable implementation in Java has provision for adding objects implementing Observer interface and notifying them by calling the update method.
9. 9. Demo • Below is the code for creating a collection of cell and setting up the values. • It also demonstrates with a sample. • http://code.google.com/p/observerpattern- sudoku/source/browse/