2013-02-02 23 views

回答

0

這是基本的想法(Command模式)

static Runnable[] methods = new Runnable[10]; 

public static void main(String[] args) throws Exception { 
    methods[0] = new Runnable() { 
     @Override 
     public void run() { 
      System.out.println("method-0"); 
     } 
    }; 
    methods[1] = new Runnable() { 
     @Override 
     public void run() { 
      System.out.println("method-1"); 
     } 
    }; 
    ... 
    methods[1].run(); 
} 

輸出

method-1 

或與反射

static Method[] methods = new Method[10]; 

public static void method1() { 
    System.out.println("method-1"); 
} 

public static void method2() { 
    System.out.println("method-2"); 
} 

public static void main(String[] args) throws Exception { 
    methods[0] = Test1.class.getDeclaredMethod("method1"); 
    methods[1] = Test1.class.getDeclaredMethod("method2"); 
    methods[1].invoke(null); 
} 
1

也許你需要使用某種Command模式,像

class Board { 
    Cell[][] cells = new Cell[5][5]; 

    void addCell(int i, int j, Cell cell) { 
    cells[i,j] = cell; 
    } 

    void executeCell(int i, int j) { 
    cells[i,j].execute(this); 
    } 
} 

interface Cell { 
    void execute(Board board); 
} 

class CellImpl implements Cell { 
    void execute(Board board) { 
    // do your stuff here 
    } 
} 

如你願意,你可以添加儘可能多的實現,只要它們實現電池接口 - 板可執行它們。