可以用接口实现:
public class FunctionPointerTest {
public static void main(String... args){
Player[] players = new Player[5];
for(int i = 0;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
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[i] = new Player();
}
stopAll(players);
startAll(players);
}
public static void stopAll(Player[] players){
for(int i=0;i
players[i].stop();
}
}
public static void startAll(Player[] players){
for(int i=0;i
players[i].start();
}
}
}