Name: Prototype Design Pattern
Type: Creational Design Pattern
Purpose:
- Improving performance by cloning objects.
- Minimize complexity in object creation.
Sample Problem and Solution:
Consider a problem where you need a 64x64 grid Board class to represent a chess board. A possible design is provided here.
public class Cell {
private String color;
public Cell(String color) {
this.color = color;
// Make it time consuming task.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
public String getColor() {
return color;
}
@Override
public String toString() {
return color.substring(0, 1);
}
}
In this code, Thread.sleep is used to make the object creation as a time consuming operation.
public class Board {
public static final int NO_OF_ROWS = 8;
public static final int NO_OF_COLUMNS = 8;
private final Cell[][] board;
public Board() {
this.board = new Cell[NO_OF_ROWS][NO_OF_COLUMNS];
for (int row = NO_OF_ROWS - 1; row >= 0; row--) {
for (int col = NO_OF_COLUMNS - 1; col >= 0; col--) {
if ((row + col) % 2 == 0) {
board[row][col] = new Cell("WHITE");
} else {
board[row][col] = new Cell("BLACK");
}
}
}
}
public void print() {
for (int row = 0; row < NO_OF_ROWS; row++) {
for (int col = 0; col < NO_OF_COLUMNS; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
// Get the start time
long startTime = System.currentTimeMillis();
Board chessBoard = new Board();
// Get the end time
long endTime = System.currentTimeMillis();
System.out.println("Time taken to create a board: " + (endTime - startTime) + " millis");
// Print the board
chessBoard.print();
}
}