1. 程式人生 > >觀察者模式小 Demo

觀察者模式小 Demo

Demo

觀察者:

package com.example.observer;

/**
 * 觀察者
 * @author Dongguabai
 * @date 2018/12/16 14:21
 */
public abstract class Observer {

    protected Subject subject;

    public Observer(Subject subject) {
        this.subject = subject;
        subject.addObserver(this);
    }

    protected abstract void notified();
}
package com.example.observer;

/**
 * @author Dongguabai
 * @date 2018/12/16 14:38
 */
public class Observer1 extends Observer{


    public Observer1(Subject subject) {
        super(subject);
    }

    @Override
    protected void notified() {
        System.out.println("Observer1 ----"+subject.getState());
    }
}
package com.example.observer;

/**
 * @author Dongguabai
 * @date 2018/12/16 14:38
 */
public class Observer2 extends Observer{


    public Observer2(Subject subject) {
        super(subject);
    }

    @Override
    protected void notified() {
        System.out.println("Observer ----"+subject.getState());
    }
}

目標物件:

package com.example.observer;

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

/**
 * 目標物件
 *
 * @author Dongguabai
 * @date 2018/12/16 14:21
 */
public class Subject {

    private List<Observer> observers = new ArrayList<>(2);
    //修改引數
    private volatile int state;

    public Subject() {
    }

    public void update(int state) {
        if (state != this.state) {
            this.state = state;
            notifyAllObservers();
            return;
        }
        System.out.println("No updates。。。。。。");
    }

    private void notifyAllObservers() {
        observers.forEach(Observer::notified);
    }

    public void addObserver(Observer observer) {
        this.observers.add(observer);
    }

    public int getState() {
        return state;
    }
}

Client :

package com.example.observer;

/**
 * @author Dongguabai
 * @date 2018/12/16 14:42
 */
public class Client {

    public static void main(String[] args) {
        Subject subject = new Subject();
        new Observer1(subject);
        new Observer2(subject);
        System.out.println("-----test start------");
        subject.update(1);
        System.out.println("===================");
        subject.update(1);
        System.out.println("===================");
        subject.update(2);
        System.out.println("===================");
        subject.update(3);
    }
}

輸出結果:

-----test start------
Observer1 ----1
Observer2 ----1
===================
No updates。。。。。。
===================
Observer1 ----2
Observer2 ----2
===================
Observer1 ----3
Observer2 ----3

利用觀察者模式檢視執行緒的執行狀態

Observer:

package com.example.observer2;

/**
 * Observer 介面
 * @author Dongguabai
 * @date 2018/12/17 9:39
 */
public interface LifeCycleListener {

    void onEvent(ObservableRunnable.RunnableEvent event);

}
package com.example.observer2;

import java.util.List;

/**
 * Observer
 *
 * @author Dongguabai
 * @date 2018/12/17 9:39
 */
public class ThreadLifeCycleObserver implements LifeCycleListener {

    private final Object LOCK = new Object();

    public void concurrentQuery(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        ids.forEach(id -> new Thread(new ObservableRunnable(this) {
            @Override
            public void run() {
                try {
                    notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                    System.out.println("query for the id " + id);
                    //int i= 1/0;
                    Thread.sleep(1000L);
                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                } catch (Exception e) {
                    notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
                }
            }
        }, id).start());
    }

    @Override
    public void onEvent(ObservableRunnable.RunnableEvent event) {
        synchronized (LOCK) {
            System.out.println("The runnable [" + event.getThread().getName() + "] data changed and state is [" + event.getState() + "]");
            if (event.getCause() != null) {
                System.out.println("The runnable [" + event.getThread().getName() + "] process failed.");
                event.getCause().printStackTrace();
            }
        }
    }
}

Subject:

package com.example.observer2;

/**
 * Subject
 * @author Dongguabai
 * @date 2018/12/17 9:39
 */
public abstract class ObservableRunnable implements Runnable {

    protected LifeCycleListener listener;

    public ObservableRunnable(final LifeCycleListener listener) {
        this.listener = listener;
    }

    protected void notifyChange(final RunnableEvent event) {
        listener.onEvent(event);
    }

    public enum RunnableState {
        RUNNING, ERROR, DONE
    }

    public static class RunnableEvent {
        private final RunnableState state;
        private final Thread thread;
        private final Throwable cause;

        public RunnableEvent(RunnableState state, Thread thread, Throwable cause) {
            this.state = state;
            this.thread = thread;
            this.cause = cause;
        }

        public RunnableState getState() {
            return state;
        }

        public Thread getThread() {
            return thread;
        }

        public Throwable getCause() {
            return cause;
        }
    }
}

Client:

package com.example.observer2;

import java.util.Arrays;

/**
 * @author Dongguabai
 * @date 2018/12/17 9:39
 */
public class ThreadLifeCycleClient {
    public static void main(String[] args) {
        new ThreadLifeCycleObserver().concurrentQuery(Arrays.asList("1", "2"));
    }
}