Skip to content

Instantly share code, notes, and snippets.

@CaglarGonul
Last active December 15, 2015 21:29
Show Gist options
  • Save CaglarGonul/5326021 to your computer and use it in GitHub Desktop.
Save CaglarGonul/5326021 to your computer and use it in GitHub Desktop.
The Strategy Pattern : It defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
package com.chp1.designpuzzle;
public interface WeaponBehaviour {
String useWeapon();
}
package com.chp1.designpuzzle;
public class SwordBehaviour implements WeaponBehaviour{
@Override
public String useWeapon() {
return ("I use sword when fighting.");
}
}
package com.chp1.designpuzzle;
public class KnifeBehaviour implements WeaponBehaviour{
@Override
public String useWeapon() {
return("I use knife when fighting.");
}
}
package com.chp1.designpuzzle;
public class BowAndArrowBehaviour implements WeaponBehaviour{
@Override
public String useWeapon() {
return("I use bow and arrow when fighting.");
}
}
package com.chp1.designpuzzle;
public class AxeBehaviour implements WeaponBehaviour{
@Override
public String useWeapon() {
return("I use my axe!!!");
}
}
package com.chp1.designpuzzle;
public abstract class Character {
WeaponBehaviour weapon;
public abstract void fight();
public void setWeapon(WeaponBehaviour wp){
this.weapon = wp;
}
}
package com.chp1.designpuzzle;
public class King extends Character{
@Override
public void fight() {
System.out.println("I fight like a king. " + weapon.useWeapon());
}
}
package com.chp1.designpuzzle;
public class Queen extends Character{
@Override
public void fight() {
System.out.println("I fight like a queen ." + weapon.useWeapon());
}
}
@Test
public void test_fighting_game(){
King k = new King();
//Lets change the weapon at run time
k.setWeapon(new AxeBehaviour());
k.fight();
//Change again
k.setWeapon(new BowAndArrowBehaviour());
k.fight();
}
I fight like a king. I use my axe!!!
I fight like a king. I use bow and arrow when fighting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment