zoukankan      html  css  js  c++  java
  • 设计模式10:观察者模式

    观察者模式所做的事情就是在解耦合,让耦合的双方都依赖于抽象,而不是依赖于具体。

    这样各自的变化不会影响另一边的变化。

    uml:

    代码:

    通知者:

    package observer;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Subject {
    
    	private List<Observer> observers = new ArrayList<>();
    	private String state = null;
    
    	public String getState() {
    		return state;
    	}
    
    	public void setState(String state) {
    		this.state = state;
    	}
    	
    	public void attach(Observer observer) {
    		observers.add(observer);
    	}
    		
    	public void detach(Observer observer) {
    		observers.remove(observer);
    	}
    	
    	public void notifyAllObserver() {
    		for(Observer observer : observers){
    			observer.update();
    		}
    	}
    }
    
    package observer;
    
    
    public class ConcreteSubject extends Subject {
    	
    	@Override
    	public void notifyAllObserver() {
    		System.out.println("老板回来啦!");
    		super.notifyAllObserver();
    	}
    	
    }
    

    观察者:

    package observer;
    
    public abstract class Observer {
    	
    	protected Subject subject = null;
    	
    	public Observer(Subject subject) {
    		this.subject = subject;
    	}
    	
    	public abstract void update();
    	
    }
    
    package observer;
    
    public class ConcreteObserver extends Observer{
    
    	private String name = null;
    	private String state = null;
    	
    	public ConcreteObserver(String name, String state, Subject subject) {
    		super(subject);
    		this.name = name;
    	}
    	
    	public String getState() {
    		return state;
    	}
    
    	public void setState(String state) {
    		this.state = state;
    	}
    
    	@Override
    	public void update() {
    		state = subject.getState();
    		System.out.print(name + "的新状态是" + state);
    		
    	}
    	
    	
    }
    

      

    DEMO:

    package observer;
    
    public class ObserverDemo {
    
    	public static void main(String[] args) {
    		Subject subject = new ConcreteSubject();
    		ConcreteObserver observer = new ConcreteObserver("老王", "看电影", subject);
    		subject.attach(observer);
    		
    		subject.setState("快工作!");
    		subject.notifyAllObserver();
    	}
    	
    }
    

      

  • 相关阅读:
    (一)linux 系统命令与文件
    python(1)- 初识python
    四、计算机硬件知识整理
    三、计算机硬件历史
    二、网络基础之网络协议
    jmeter while循环使用
    gitlab分支管理
    gitlab基本操作
    JAVA多种向influxDB中插入数据方式
    JAVA类变量和实例变量
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6700104.html
Copyright © 2011-2022 走看看