Java中Delegate委托实现

1、IDelegate.java

package com.ntan520.delegate;

/**
 * @author Nick Tan
 */public interface IDelegate {

    void stop();

}

2、INotifier.java

package com.ntan520.delegate;

/**
 * @author Nick Tan
 */public interface INotifier {

    public void addDelegate(IDelegate delegate);

    public void runNotify();

}

3、NotifierAbstract

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

package com.ntan520.delegate;

/**
 * @author Nick Tan
 */public class DefaultNotifier extends NotifierAbstract {

}

5、测试

1)Delegator1.java

package com.ntan520.delegate;

public class Delegator1 implements IDelegate {

    @Override
    public void stop() {
        System.out.println("委托1事件被执行");
    }

}

2)Delegator2.java

package com.ntan520.delegate;

public class Delegator2 implements IDelegate {

    @Override
    public void stop() {
        System.out.println("委托2事件被执行");
    }
}

3)Main.java

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();
    }

}

发表评论