接口类
package com.button; /** * Created by zhangminjie on 15/3/19. */ public interface Action { void click(); }
按钮类
package com.button; /** * Created by zhangminjie on 15/3/19. */ public class Button { private Action action; public Button(Action action) { this.action = action; } public void onClick(){ System.out.println("我要开始点了!!"); action.click(); } }
事件实现类
package com.button; /** * Created by zhangminjie on 15/3/19. */ public class Click implements Action { @Override public void click() { new Thread(){ @Override public void run() { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("被点到了。。。"); } }.start(); goPlay(); } public void goPlay() { System.out.println("还没点啊,先去玩会!"); } }
测试类
package com.button; /** * Created by zhangminjie on 15/3/19. */ public class TestButton { public static void main(String[] args) { Action action = new Click(); Button button = new Button(action); button.onClick(); } }
打印:
我要开始点了!!
还没点啊,先去玩会!
被点到了。。。
定义好动作接口,按钮类调用接口方法。
实现接口方法,即可自定义单击动作的回调方法。