如何通知对象另一个对象的事件?爪哇

时间:2019-05-31 15:56:59

标签: java notify

我有一个名为Main的Java类,它实例了几个名为Subscriber的类。订户从互联网获取数据,并在获取新数据时将其存储在变量中。保存新数据后,我希望它通知Main或它检测到它。我该怎么办?

我曾考虑过使用观察者模式,但就我而言,我有一个观察者并且有许多观察者

1 个答案:

答案 0 :(得分:-1)

尝试一下。

public class Stack1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Producer p = new A();
        for (int i = 0; i < 10; i++) {
            Subscriber s = new B(p);
        }
        p.sendAll(new Data(1));
        p.sendAll(new Data(2));
        p.sendAll(new Data(3));
        p.sendAll(new Data(4));

    }

    public static class Data implements Serializable {

        private static final long serialVersionUID = 3897786191139169609L;

        private Integer value;

        public Data(Integer value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "Data{" + "value=" + value + '}';
        }





    }

    public interface Subscriber {

        public void doSomething(Data data);
    }

    public interface Producer {

        public void addSubscriber(Subscriber subscriber);

        public void sendAll(Data data);
    }

    public static class A implements Producer {

        private List<Subscriber> lst = new ArrayList<>();

        @Override
        public void addSubscriber(Subscriber subscriber) {
            lst.add(subscriber);
        }

        @Override
        public void sendAll(Data data) {
            for (Subscriber subscriber : lst) {
                subscriber.doSomething(data);
            }
        }

    }

    public static class B implements Subscriber {

        private final String id;

        public B(Producer producer) {
            producer.addSubscriber(this);
            id = UUID.randomUUID().toString();
        }

        @Override
        public void doSomething(Data data) {
            System.out.println(id.concat(" it.bookingexpert.test.Stack1.B.doSomething() ".concat(data.toString())));
        }

    }

}