2017-10-05 69 views
0

我有一個在某個特定時間添加到舞臺上的演員。加入舞臺後需要計算價值。 有沒有辦法在添加到階段之後向Actor添加回調?如何在演員添加到舞臺時添加回調?

示例代碼

public class SlotReel extends Table{ 

    public SlotReel() { 
    } 

    public void compute(){ 
     //call after SlootReel is added to stage 
    } 

} 

例階段添加代碼

stage.addActor(slotReel);// I wish to trigger the compute method in SlotReel after here. 

回答

0

public class Solution { 

    // Create interface 
    interface Computable { 
     void compute(); 
    } 

    // SlotReel implement Computable interface 
    static public class SlotReel implements Computable { 

     String name; 

     public SlotReel(String name) { 
      this.name = name; 
     } 

     // Implement compute method 
     @Override 
     public void compute() { 
      // call after SlootReel is added to stage 
      // Just an example 
      System.out.println("Hello " + name); 
     } 

    } 

    static public class Stage { 

     List<Computable> list = new ArrayList<>(); 

     public void addActor(Computable slot) { 
      list.add(slot); 
      // call compute method 
      slot.compute(); 
     } 
    } 

    public static void main(String[] args) { 
     Stage stage = new Stage(); 
     stage.addActor(new SlotReel("A")); 
     stage.addActor(new SlotReel("B")); 
     stage.addActor(new SlotReel("C")); 
     stage.addActor(new SlotReel("D")); 
    } 
}