一.关于观察者模式

1.将观察者与被观察者分离开来,当被观察者发生变化时,将通知所有观察者,观察者会根据这些变化做出对应的处理。

2.jdk里已经提供对应的Observer接口(观察者接口)与Observable(被观察者类)用于实现观察者模式

3.关于Observer接口,该接口只有一个update方法,当被观察者发生相关变化时,会通知所有的观察者,观察者接受到通知时,调用update方法进行处理。贴出源代码:

  1. /*
  2. * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. */
  25. package java.util;
  26.  
  27. /**
  28. * A class can implement the <code>Observer</code> interface when it
  29. * wants to be informed of changes in observable objects.
  30. *
  31. * @author Chris Warth
  32. * @see java.util.Observable
  33. * @since JDK1.0
  34. */
  35. public interface Observer {
  36. /**
  37. * This method is called whenever the observed object is changed. An
  38. * application calls an <tt>Observable</tt> object's
  39. * <code>notifyObservers</code> method to have all the object's
  40. * observers notified of the change.
  41. *
  42. * @param o the observable object.
  43. * @param arg an argument passed to the <code>notifyObservers</code>
  44. * method.
  45. */
  46. void update(Observable o, Object arg);
  47. }

4:关于被观察者Observable的常用方法:

1.  public synchronized void addObserver(Observer o);//添加观察者对象

2. public void notifyObservers();//通知所有观察者

3. protected synchronized void setChanged();//设置观察项已经做出改变,此方法很重要

贴出源代码,注意内部实现:

  1. /*
  2. * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. */
  25.  
  26. package java.util;
  27.  
  28. /**
  29. * This class represents an observable object, or "data"
  30. * in the model-view paradigm. It can be subclassed to represent an
  31. * object that the application wants to have observed.
  32. * <p>
  33. * An observable object can have one or more observers. An observer
  34. * may be any object that implements interface <tt>Observer</tt>. After an
  35. * observable instance changes, an application calling the
  36. * <code>Observable</code>'s <code>notifyObservers</code> method
  37. * causes all of its observers to be notified of the change by a call
  38. * to their <code>update</code> method.
  39. * <p>
  40. * The order in which notifications will be delivered is unspecified.
  41. * The default implementation provided in the Observable class will
  42. * notify Observers in the order in which they registered interest, but
  43. * subclasses may change this order, use no guaranteed order, deliver
  44. * notifications on separate threads, or may guarantee that their
  45. * subclass follows this order, as they choose.
  46. * <p>
  47. * Note that this notification mechanism has nothing to do with threads
  48. * and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
  49. * mechanism of class <tt>Object</tt>.
  50. * <p>
  51. * When an observable object is newly created, its set of observers is
  52. * empty. Two observers are considered the same if and only if the
  53. * <tt>equals</tt> method returns true for them.
  54. *
  55. * @author Chris Warth
  56. * @see java.util.Observable#notifyObservers()
  57. * @see java.util.Observable#notifyObservers(java.lang.Object)
  58. * @see java.util.Observer
  59. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  60. * @since JDK1.0
  61. */
  62. public class Observable {
  63. private boolean changed = false;
  64. private Vector<Observer> obs;
  65.  
  66. /** Construct an Observable with zero Observers. */
  67.  
  68. public Observable() {
  69. obs = new Vector<>();
  70. }
  71.  
  72. /**
  73. * Adds an observer to the set of observers for this object, provided
  74. * that it is not the same as some observer already in the set.
  75. * The order in which notifications will be delivered to multiple
  76. * observers is not specified. See the class comment.
  77. *
  78. * @param o an observer to be added.
  79. * @throws NullPointerException if the parameter o is null.
  80. */
  81. public synchronized void addObserver(Observer o) {
  82. if (o == null)
  83. throw new NullPointerException();
  84. if (!obs.contains(o)) {
  85. obs.addElement(o);
  86. }
  87. }
  88.  
  89. /**
  90. * Deletes an observer from the set of observers of this object.
  91. * Passing <CODE>null</CODE> to this method will have no effect.
  92. * @param o the observer to be deleted.
  93. */
  94. public synchronized void deleteObserver(Observer o) {
  95. obs.removeElement(o);
  96. }
  97.  
  98. /**
  99. * If this object has changed, as indicated by the
  100. * <code>hasChanged</code> method, then notify all of its observers
  101. * and then call the <code>clearChanged</code> method to
  102. * indicate that this object has no longer changed.
  103. * <p>
  104. * Each observer has its <code>update</code> method called with two
  105. * arguments: this observable object and <code>null</code>. In other
  106. * words, this method is equivalent to:
  107. * <blockquote><tt>
  108. * notifyObservers(null)</tt></blockquote>
  109. *
  110. * @see java.util.Observable#clearChanged()
  111. * @see java.util.Observable#hasChanged()
  112. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  113. */
  114. public void notifyObservers() {
  115. notifyObservers(null);
  116. }
  117.  
  118. /**
  119. * If this object has changed, as indicated by the
  120. * <code>hasChanged</code> method, then notify all of its observers
  121. * and then call the <code>clearChanged</code> method to indicate
  122. * that this object has no longer changed.
  123. * <p>
  124. * Each observer has its <code>update</code> method called with two
  125. * arguments: this observable object and the <code>arg</code> argument.
  126. *
  127. * @param arg any object.
  128. * @see java.util.Observable#clearChanged()
  129. * @see java.util.Observable#hasChanged()
  130. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  131. */
  132. public void notifyObservers(Object arg) {
  133. /*
  134. * a temporary array buffer, used as a snapshot of the state of
  135. * current Observers.
  136. */
  137. Object[] arrLocal;
  138.  
  139. synchronized (this) {
  140. /* We don't want the Observer doing callbacks into
  141. * arbitrary code while holding its own Monitor.
  142. * The code where we extract each Observable from
  143. * the Vector and store the state of the Observer
  144. * needs synchronization, but notifying observers
  145. * does not (should not). The worst result of any
  146. * potential race-condition here is that:
  147. * 1) a newly-added Observer will miss a
  148. * notification in progress
  149. * 2) a recently unregistered Observer will be
  150. * wrongly notified when it doesn't care
  151. */
  152. if (!changed)
  153. return;
  154. arrLocal = obs.toArray();
  155. clearChanged();
  156. }
  157.  
  158. for (int i = arrLocal.length-1; i>=0; i--)
  159. ((Observer)arrLocal[i]).update(this, arg);
  160. }
  161.  
  162. /**
  163. * Clears the observer list so that this object no longer has any observers.
  164. */
  165. public synchronized void deleteObservers() {
  166. obs.removeAllElements();
  167. }
  168.  
  169. /**
  170. * Marks this <tt>Observable</tt> object as having been changed; the
  171. * <tt>hasChanged</tt> method will now return <tt>true</tt>.
  172. */
  173. protected synchronized void setChanged() {
  174. changed = true;
  175. }
  176.  
  177. /**
  178. * Indicates that this object has no longer changed, or that it has
  179. * already notified all of its observers of its most recent change,
  180. * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
  181. * This method is called automatically by the
  182. * <code>notifyObservers</code> methods.
  183. *
  184. * @see java.util.Observable#notifyObservers()
  185. * @see java.util.Observable#notifyObservers(java.lang.Object)
  186. */
  187. protected synchronized void clearChanged() {
  188. changed = false;
  189. }
  190.  
  191. /**
  192. * Tests if this object has changed.
  193. *
  194. * @return <code>true</code> if and only if the <code>setChanged</code>
  195. * method has been called more recently than the
  196. * <code>clearChanged</code> method on this object;
  197. * <code>false</code> otherwise.
  198. * @see java.util.Observable#clearChanged()
  199. * @see java.util.Observable#setChanged()
  200. */
  201. public synchronized boolean hasChanged() {
  202. return changed;
  203. }
  204.  
  205. /**
  206. * Returns the number of observers of this <tt>Observable</tt> object.
  207. *
  208. * @return the number of observers of this object.
  209. */
  210. public synchronized int countObservers() {
  211. return obs.size();
  212. }
  213. }

5.举一个例子吧:当婴儿哭泣时,则通知家人来哄宝宝,那么这里很明显婴儿是一个被观察者,当婴儿哭泣时,立刻通知家人(观察者)

  1. package com.bdqn.s2.javaoop.study.proxy;
  2.  
  3. import java.lang.reflect.Proxy;
  4. import java.util.Observable;
  5. import java.util.Observer;
  6.  
  7. /**
  8. * 婴儿类,被观察者
  9. */
  10. public class Baby extends Observable {
  11.  
  12. private int hungry;
  13.  
  14. private String name;
  15.  
  16. public String getName() {
  17. return name;
  18. }
  19.  
  20. public Baby(String name, int hungry) {
  21. this.hungry = hungry;
  22. this.name = name;
  23. addObserver(new Parents());//添加观察者对象,需要家长监管
  24. }
  25.  
  26. /**
  27. * 婴儿开始哭泣
  28. */
  29. public void cry() {
  30. if (hungry < 100) {
  31. System.out.printf("baby%s饿了,开始哭泣...%n", name);
  32. setChanged();//饥饿值过低,触发变化,此方法必须被调用
  33. notifyObservers();//通知观察者
  34. }
  35. }
  36. }
  37.  
  38. /**
  39. * 家长,观察者
  40. */
  41. class Parents implements Observer {
  42. @Override
  43. public void update(Observable o, Object arg) {
  44.  
  45. if (o instanceof Baby) {
  46. Baby baby = (Baby) o;
  47. System.out.println(baby.getName()+"开始哭泣,赶紧哄宝宝啦");
  48. }
  49. }
  50.  
  51. }
  52.  
  53. public class Main {
  54.  
  55. public static void main(String[] args) {
  56. Baby baby = new Baby("豆豆",9);
  57. baby.cry();
  58. }
  59. }
  60.  
  61. /*
  62. 输出结果
  63. baby豆豆饿了,开始哭泣...
  64. 豆豆开始哭泣,赶紧哄宝宝啦
  65. */

二 关于动态代理模式

1)代理模式是设计模式中非常常见的一种模式,这种模式可以实现对原有方法的扩展,举个例子经纪人可以替明星们办理一些事情,那么此时经纪人可以视为明星的代理。

2)代理模式可以分为静态代理和动态代理,在这里我们只对JDK提供的动态代理进行讨论。

3)由于JDK提供的代理模式所代理的类继承了Proxy,因此我们只能接口进行代理,针对类的代理可以自行参考cglib框架

4)InvocationHandler:是代理实例的调用处理程序 实现的接口。 每个代理实例都具有一个关联的调用处理程序。对代理实例调用方法时,将对方法调用进行编码并将其指派到它的调用处理程序的 invoke 方法。

  1. //proxy:代理类,method:代理执行的方法 args:方法参数
  2. public Object invoke(Object proxy, Method method, Object[] args);

5)Proxy:该类主要是获取或者新创建动态代理对象

  1. //该方法主要用于获取代理对象,注意一定是针对接口进行代理
  2. public static Object newProxyInstance(ClassLoader loader,
  3. Class<?>[] interfaces,
  4. InvocationHandler h)
  5. throws IllegalArgumentException

6)针对上述例子进行改造:添加保姆类并改造Baby类的构造方法:

  1. package com.bdqn.s2.javaoop.study.proxy;
  2.  
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. import java.util.Observer;
  6.  
  7. /**
  8. * 保姆类
  9. */
  10. public class Nanny implements InvocationHandler {
  11.  
  12. private Observer parents;
  13.  
  14. public Nanny(){
  15. parents = new Parents();
  16. }
  17.  
  18. @Override
  19. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  20. System.out.println("保姆开始照顾孩子");
  21. Object object = method.invoke(parents, args);
  22. return object;
  23. }
  24. }

Baby类构造函数改造:

  1. public Baby(String name, int hungry) {
  2. this.hungry = hungry;
  3. this.name = name;
  4. addObserver((Observer) Proxy.newProxyInstance(Baby.class.getClassLoader(),new Class[]{Observer.class},new Nanny()));
  5. }

输出结果:

  1. baby豆豆饿了,开始哭泣...
  2. 保姆开始照顾孩子
  3. 豆豆开始哭泣,赶紧哄宝宝啦

浅谈java中内置的观察者模式与动态代理的实现的更多相关文章

  1. 浅谈Java中set.map.List的区别

    就学习经验,浅谈Java中的Set,List,Map的区别,对JAVA的集合的理解是想对于数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),JAVA集合可以存储和操 ...

  2. Java基础学习总结(29)——浅谈Java中的Set、List、Map的区别

    就学习经验,浅谈Java中的Set,List,Map的区别,对JAVA的集合的理解是想对于数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),JAVA集合可以存储和操 ...

  3. 浅谈Java中的final关键字

    浅谈Java中的final关键字 谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来 ...

  4. 浅谈Java中的equals和==(转)

    浅谈Java中的equals和== 在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String("hello"); 2 String str ...

  5. 浅谈Java中的对象和引用

    浅谈Java中的对象和对象引用 在Java中,有一组名词经常一起出现,它们就是“对象和对象引用”,很多朋友在初学Java的时候可能经常会混淆这2个概念,觉得它们是一回事,事实上则不然.今天我们就来一起 ...

  6. 浅谈Java中的equals和==

    浅谈Java中的equals和== 在初学Java时,可能会经常碰到下面的代码: String str1 = new String("hello"); String str2 = ...

  7. 浅谈Java中的深拷贝和浅拷贝(转载)

    浅谈Java中的深拷贝和浅拷贝(转载) 原文链接: http://blog.csdn.net/tounaobun/article/details/8491392 假如说你想复制一个简单变量.很简单: ...

  8. 浅谈Java中的深拷贝和浅拷贝

    转载: 浅谈Java中的深拷贝和浅拷贝 假如说你想复制一个简单变量.很简单: int apples = 5; int pears = apples; 不仅仅是int类型,其它七种原始数据类型(bool ...

  9. 【转】浅谈Java中的hashcode方法(这个demo可以多看看)

    浅谈Java中的hashcode方法 哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率.在Java的Object类中有一个方法: public native i ...

随机推荐

  1. 22.C++- 继承与组合,protected访问级别

    在C++里,通过继承和组合实现了代码复用,使得开发效率提高,并且能够通过代码看到事物的关系 组合比继承简单,所以在写代码时先考虑能否组合,再来考虑继承. 组合的特点 将其它类的对象作为当前类的成员使用 ...

  2. HTML5 canvas绘制雪花飘落

    Canvas是HTML5新增的组件,它就像一块幕布,可以用JavaScript在上面绘制各种图表.动画等. 没有Canvas的年代,绘图只能借助Flash插件实现,页面不得不用JavaScript和F ...

  3. nyoj 非洲小孩

    非洲小孩 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 家住非洲的小孩,都很黑.为什么呢?第一,他们地处热带,太阳辐射严重.第二,他们不经常洗澡.(常年缺水,怎么洗 ...

  4. js前端对后台数据的获取,如果是汉字则需要添上引号

    js前端对后台数据的获取,如果是汉字则需要添上引号

  5. LeetCode & Q1-Two Sum-Easy

    Array Hash Table Question Given an array of integers, return indices of the two numbers such that th ...

  6. Linux上 ps 命令的用法

    ps a 显示现行终端机下的所有程序,包括其他用户的程序.2)ps -A 显示所有程序. 3)ps c 列出程序时,显示每个程序真正的指令名称,而不包含路径,参数或常驻服务的标示. 4)ps -e 此 ...

  7. kafka之zookeeper 节点

    1.zookeeper 节点 kafka 在 zookeeper 中的存储结构如下图所示:

  8. 实现GridControl行动态改变行字体和背景色

    需求:开发时遇到一个问题, 需要根据GridControl行数据不同,实现不同的效果 在gridView的RowCellStyle的事件中实现,需要的效果 private void gridView1 ...

  9. 文本编辑器(KindEditord)

    1.下载 官网下载:http://kindeditor.net/down.php 本地下载:http://files.cnblogs.com/files/wupeiqi/kindeditor_a5.z ...

  10. Hibernate(三): org.hibernate.HibernateException: No CurrentSessionContext configured!

    Hibernate版本5.2.9 获取Session的方式是sessionFactory.getCurrentSession(); 比较老一些的版本使用的是sessionFactory.openSes ...