package com.modle; import java.util.Vector; import org.omg.CORBA.OBJECT_NOT_EXIST; /** * 观察者模式 * @author k560 * */ /*观察者接口*/ public interface Observer { /*观察到被观察者行为后执行的行为*/ void doSome(); } /*观察者1*/ class Observer1 implements Observer{ @Override public void doSome() { System.out.println("观察者1观察到了"); } } /*观察者2*/ class Observer2 implements Observer{ @Override public void doSome() { System.out.println("观察者2观察到了"); } } /*抽象被观察者*/ abstract class Subject{ Vector<Observer> observers=new Vector<Observer>(); /*添加观察者*/ public void addObserver(Observer observer){ observers.add(observer); } /*删除观战者*/ public void removeObserver(Observer observer){ observers.remove(observer); } /*通知所有观察者*/ protected void notifyAllObserver() { for (Observer observer : observers) { observer.doSome(); } } protected abstract void show(); } class SubjectA extends Subject{ @Override protected void show() { System.out.println("被观察者行动了"); this.notifyAllObserver(); } } public class TestObserver{ public static void main(String[] args) { /*创建被观察者*/ Subject subject=new SubjectA(); /*添加观察者*/ Observer observer1=new Observer1(); Observer observer2=new Observer2(); subject.addObserver(observer1); subject.addObserver(observer2); /*被观察者执行方法*/ subject.show(); /*删除观察者1*/ subject.removeObserver(observer1); subject.show(); } }
时间: 2024-09-26 21:56:17