-2

I have a Java class, named Main, which instances several classes with name Subscriber. Subscriber obtains data from the internet and when it obtains a new data it stores it in a variable. When a new data is saved I want it to notify Main, or that it detects it. How could I do it?

I have thought about using the Observer pattern but in my case I have an observer and many observed

  • Well, create a notify method and let the other class call it. You can make it nicer by introducing an interface system and a list of registered listeners etc. but in the end, its just about calling that method. – Zabuzard May 31 '19 at 15:59

1 Answers1

-1

Try this.

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

    }

}
renato
  • 1
  • 1
  • 1
    Wow, what bad code dump without explanation. The code does not even compile! Weird spacing. Poorly named classes. `Data` implements `Serializable` for no reason. Heck, you could do without `Data` and just use `String` if you don't want to use generics for some reason. You may want to read [answer]. – Robert May 31 '19 at 16:36