观察者模式属于行为型模式,所谓观察模式,观察者订阅了某种服务,那么该服务有变化会通知观察者。
简单的类图:
- public interface EventObserver {
- public void speek();
- }
- public interface EventSubject {
- public void registerOberver(EventObserver observer);
- public void removeOberver(EventObserver observer);
- public void notifiedOberver();
- }
- public class observer1 implements EventObserver{
- @Override
- public void speek() {
- System.out.println("observer1");
- }
- }
- public class observer2 implements EventObserver{
- @Override
- public void speek() {
- System.out.println("observer2");
- }
- }
- public class observer3 implements EventObserver{
- @Override
- public void speek() {
- System.out.println("observer3");
- }
- }
- public class Subject implements EventSubject{
- private List<EventObserver> list = new ArrayList<>();
- private static Subject subject = null;
- private Subject(){
- }
- public static Subject newInstance(){
- if(subject ==null){
- subject = new Subject();
- }
- return subject;
- }
- @Override
- public void registerOberver(EventObserver observer) {
- list.add(observer);
- }
- @Override
- public void removeOberver(EventObserver observer) {
- list.remove(observer);
- }
- @Override
- public void notifiedOberver() {
- for(EventObserver c:list){
- c.speek();
- }
- }
- }
- public class test {
- public static void main(String[] args){
- observer1 o1 = new observer1();
- observer2 o2 = new observer2();
- observer3 o3 = new observer3();
- Subject subject = Subject.newInstance();
- subject.registerOberver(o1);
- subject.registerOberver(o2);
- subject.registerOberver(o3);
- subject.notifiedOberver();
- System.out.println("======================");
- subject.removeOberver(o1);
- subject.notifiedOberver();
- }
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-2140454/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-2140454/