Strategy pattern with a game of Cards

I have to design a game of Cards .This game has multiple flavours (like real card games where each game of cards has their own rule ) .Here I have two flavours with these rules –

Rule for flavour A-

In a game of Two player each chooses one card .Player holding higher card is winner.

Rule for flavour B-

In a game of Two player each chooses one card.Player holding lower card is winner.

So I have solved this problem using strategy Pattern .I wrote strategies for each rule and passed it to game.


public interface Comparable<T> {

 public int compare(T obj);

}

public interface WinableUnit extends Comparable<WinableUnit>{

}
//strategy interface
public interface WinningStrategy {

 public WinableUnit getWinner(WinableUnit first,WinableUnit second);

}
//Stategy implementation for Higher score winning rule
public class HighestScoreWinningStrategy implements WinningStrategy{

 public WinableUnit getWinner(WinableUnit first, WinableUnit second) {
 if(first.compare(second)==0){
 throw new RuntimeException("Both Unit have equal score");
 }

 return first.compare(second) >0 ?first : second;

 }

}

//stategy implementation for lower score winning rule
public class LowScoreWinningStrategy implements WinningStrategy{

 public WinableUnit getWinner(WinableUnit first, WinableUnit second) {
 if(first.compare(second)==0){
 throw new RuntimeException("Both players have equal score");
 }
 return first.compare(second)<0 ?first:second;
 }

}

public class Card implements Comparable<Card>{
 Integer number;

 public Card(Integer number) {
 this.number = number;
 }

 public int compare(Card anotherCard) {
 return this.number.compareTo(anotherCard.number);
 }

}
package com.ratn.game;

public class Player implements WinableUnit{

 private Card card;

 public Player(Card card) {
 this.card = card;
 }

 public int compare(WinableUnit anotherUnit) {

 return card.compare(((Player)anotherUnit).card);
 }

}

public class Game {

 private WinningStrategy strategy;
 private Player player1;
 private Player player2;

 public Game(WinningStrategy strategy) {
 this.strategy = strategy;

 player1 = new Player(new Card(getRandomNumber()));
 player2 = new Player(new Card(getRandomNumber()));

 }

 public Player winner(){
 return (Player) strategy.getWinner(player1, player2);
 }

 private int getRandomNumber(){
//returns a random number between range
 return 0;
 }

}

Advertisements
This entry was posted in Design. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s