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();
	}
}

如果不用这种“函数指针”,以上代码就会是:

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();
		}
		stopAll(players);
		startAll(players);
	}
	public static void stopAll(Player[] players){
		for(int i=0;i<players.length;i++){
			players[i].stop();
		}
	}
	public static void startAll(Player[] players){
		for(int i=0;i<players.length;i++){
			players[i].start();
		}
	}
}
 
看完之后,找到了重用代码的思路了:)

来源: http://my.oschina.net/soitravel/blog/36029





你可能感兴趣的:(java中实现类似函数指针的功能)