java中实现类似函数指针的功能

可以用接口实现:
public class FunctionPointerTest { public static void main(String... args){ Player[] players = new Player[5]; for(int i = 0;i<players.length;i++){ players[i] = new Player(); } pressButton(players,new StopButton()); pressButton(players,new StartButton()); } public static void pressButton(Player[] players,PlayerButton button){ for(int i=0;i<players.length;i++){ button.buttonPressed(players[i]); } } } class Player { public void start(){ System.out.println("start"); } public void stop(){ System.out.println("stop"); } } interface PlayerButton { public void buttonPressed(Player player); } class StopButton implements PlayerButton{ @Override public void buttonPressed(Player player) { player.stop(); } } class StartButton implements PlayerButton{ @Override public void buttonPressed(Player player) { player.start(); } }
posted @ 2014-04-23 10:59  wonglou  阅读(2210)  评论(0编辑  收藏  举报