文章内容
1、IDelegate.java
1 2 3 4 5 6 7 8 9 | package com.ntan520.delegate; /** * @author Nick Tan */ public interface IDelegate { void stop(); } |
2、INotifier.java
01 02 03 04 05 06 07 08 09 10 11 | package com.ntan520.delegate; /** * @author Nick Tan */ public interface INotifier { public void addDelegate(IDelegate delegate); public void runNotify(); } |
3、NotifierAbstract
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.ntan520.delegate; import java.util.ArrayList; import java.util.List; /** * @author Nick Tan */ public abstract class NotifierAbstract implements INotifier { private List<IDelegate> delegates = new ArrayList<IDelegate>(); @Override public void addDelegate(IDelegate delegate) { if (delegate != null ) { delegates.add(delegate); } } @Override public void runNotify() { for (IDelegate delegate : delegates) { delegate.stop(); } } } |
4、DefaultNotifier.java
1 2 3 4 5 6 7 | package com.ntan520.delegate; /** * @author Nick Tan */ public class DefaultNotifier extends NotifierAbstract { } |
5、测试
1)Delegator1.java
01 02 03 04 05 06 07 08 09 10 | package com.ntan520.delegate; public class Delegator1 implements IDelegate { @Override public void stop() { System.out.println( "委托1事件被执行" ); } } |
2)Delegator2.java
1 2 3 4 5 6 7 8 9 | package com.ntan520.delegate; public class Delegator2 implements IDelegate { @Override public void stop() { System.out.println( "委托2事件被执行" ); } } |
3)Main.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | package com.ntan520.delegate; public class Main { public static void main(String[] args) { Delegator1 delegator1 = new Delegator1(); Delegator2 delegator2 = new Delegator2(); INotifier notifier = new DefaultNotifier(); notifier.addDelegate(delegator1); notifier.addDelegate(delegator2); notifier.runNotify(); } } |