mardi 9 novembre 2021

Is this a correct way to implement the observer pattern

I am trying to implement the observer pattern, where the (array of observers, add observer, remove observer, notify all) are in a separate class So that the subject (e.g Student) class can be just for the subject logic. And I am trying to make the observed subject be of any type, for later reuse of the observer class

    import java.util.ArrayList;
    import java.util.List;

    public class ObserverPattern {
        public static void main(String[] args) {
            Student subject = new Student(3.5);

            new Tafawk(subject);

            System.out.println("First state change: 15");
            subject.setCGPA(3.4);
            System.out.println("Second state change: 10");
            subject.setCGPA(3.3);
        }
    }

    abstract class Observed<T> {
        private List<Observer2<T>> observers = new ArrayList<Observer2<T>>();

        public void stateChanged(T state) {
            notifyAllObservers();
        }

        public void notifyAllObservers() {
            for (Observer2<T> observer : observers) {
                observer.update();
            }
        }

        public void attach(Observer2<T> observer) {
            observers.add(observer);
        }

    }

    class Student extends Observed<Student> {
        double CGPA;

        Student(double CGPA) {
            this.CGPA = CGPA;
        }

        public void setCGPA(double cGPA) {
            CGPA = cGPA;
            super.stateChanged(this);
        }

        public double getCGPA() {
            return CGPA;
        }

        @Override
        public String toString() {
            return super.toString();
        }
    }

    abstract class Observer2<T> {
        protected Observed<T> subject;

        public abstract void update();
    }

    class Tafawk extends Observer2<Student> {
        Student prev;

        public Tafawk(Student subject) {
            this.subject = subject;
            this.prev = subject;
            this.subject.attach(this);
        }

        @Override
        public void update() {
            System.out.println("CGAP Changed to "+ ((Student) subject).getCGPA());
        }
    }

sorry about the naming convention

Aucun commentaire:

Enregistrer un commentaire