Observer Pattern

Observer pattern 은 특정 상태의 변화를 observer 에게 통보해주는 pattern 이다.

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

public class main {
    public static void main(String[] args) {
        Andrew andrew = new Andrew();
        Pet cat = new Cat();
        Pet dog = new Dog();

        andrew.registerObserver(cat);
        andrew.registerObserver(dog);

        andrew.clap();
    }
}

interface Owner {
    void registerObserver(Pet pet);

    void removeObserver(Pet pet);

    void clap();
}

interface Pet {
    public void reaction();
}

class Andrew implements Owner {
    private List<Pet> observerCollection = new ArrayList<Pet>();

    @Override
    public void registerObserver(Pet pet) {
        observerCollection.add(pet);
    }

    @Override
    public void removeObserver(Pet pet) {
        observerCollection.remove(pet);
    }

    @Override
    public void clap() {
        for (Pet animal : observerCollection) {
            animal.reaction();
        }
    }
}

class Dog implements Pet {
    @Override
    public void reaction() {
        System.out.println("bark bark");
    }
}

class Cat implements Pet {
    @Override
    public void reaction() {
        System.out.println("meow meow ");
    }
}