I've seen countless Strategy pattern described on the web and none of them really get me so far. They use Dog, Cat, Coffee, even worse, JComponent.. sure I can "programming to interface not implementation."
Still not getting it without writing my own strategy pattern with my own words. (Doesn't matter what terms I use, the point is I get the concept!)
Here is my version of strategy design pattern:
public interface Console { public void launchGame(); } public class XBox360 implements Console { public void launchGame() { System.out.print("I see the ring of death!"); } } public class PlayStation3 implements Console { public void launchGame() { System.out.println("SONY is being hacked by a kid"); } } public class Wii implements Console { public void launchGame() { System.out.println("I think my Wii controller is in my neighbor's backyard"); } } public class Me { private Console console = null; public Me(Cosole console) { this.console = console; } public setConsole(Console console) { this.console = console; } public void turnOn() { if(console != null) { console.launchGame(); } } } public class Test { public static void main(String[] args) { Me me = new Me(new XBox360()); me.turnOn(); //"I see the ring of death!" me.setConsole(new PlayStation3()); me.turnOn(); //"SONY is being hacked by a kid" me.setConsole(new Me(new Wii()); me.turnOn(); //I think my Wii controller is in my neighbor's backyard") } }
No comments:
Post a Comment