디자인 모델 (6. 행위 형 - 관찰자 모델)

9314 단어
 1 /**
 2  *     
 3  *
 4  * @author zhoude
 5  * @date 2020/4/12 14:48
 6  */
 7 public interface Observer {
 8 
 9     /**
10      *           
11      *
12      * @param message     
13      */
14     void notify(String message);
15 }
 1 public interface Subject {
 2 
 3     /**
 4      *         
 5      *
 6      * @param observer     
 7      */
 8     void addObserver(Observer observer);
 9 
10     /**
11      *         
12      *
13      * @param observer     
14      */
15     void removeObserver(Observer observer);
16 
17     /**
18      *          
19      *
20      * @param message     
21      */
22     void notifyObservers(String message);
23 }
 1 public class SubjectImpl implements Subject {
 2 
 3     private List observers = new ArrayList<>();
 4 
 5     @Override
 6     public void addObserver(Observer observer) {
 7         observers.add(observer);
 8     }
 9 
10     @Override
11     public void removeObserver(Observer observer) {
12         observers.remove(observer);
13     }
14 
15     @Override
16     public void notifyObservers(String message) {
17         for (Observer observer : observers) {
18             observer.notify(message);
19         }
20     }
21 }
1 public class ObserverImpl1 implements Observer {
2 
3     @Override
4     public void notify(String message) {
5         System.err.println("observer1 message:" + message);
6     }
7 }
1 public class ObserverImpl2 implements Observer {
2 
3     @Override
4     public void notify(String message) {
5         System.err.println("observer2 message:" + message);
6     }
7 }
1 public class Test {
2 
3     public static void main(String[] args) {
4         Subject subject = new SubjectImpl();
5         subject.addObserver(new ObserverImpl1());
6         subject.addObserver(new ObserverImpl2());
7         subject.notifyObservers("msg");
8     }
9 }

좋은 웹페이지 즐겨찾기