浅谈java中内置的观察者模式与动态代理的实现
一.关于观察者模式
1.将观察者与被观察者分离开来,当被观察者发生变化时,将通知所有观察者,观察者会根据这些变化做出对应的处理。
2.jdk里已经提供对应的Observer接口(观察者接口)与Observable(被观察者类)用于实现观察者模式
3.关于Observer接口,该接口只有一个update方法,当被观察者发生相关变化时,会通知所有的观察者,观察者接受到通知时,调用update方法进行处理。贴出源代码:
/*
* Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.util; /**
* A class can implement the <code>Observer</code> interface when it
* wants to be informed of changes in observable objects.
*
* @author Chris Warth
* @see java.util.Observable
* @since JDK1.0
*/
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}
4:关于被观察者Observable的常用方法:
1. public synchronized void addObserver(Observer o);//添加观察者对象
2. public void notifyObservers();//通知所有观察者
3. protected synchronized void setChanged();//设置观察项已经做出改变,此方法很重要
贴出源代码,注意内部实现:
/*
* Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ package java.util; /**
* This class represents an observable object, or "data"
* in the model-view paradigm. It can be subclassed to represent an
* object that the application wants to have observed.
* <p>
* An observable object can have one or more observers. An observer
* may be any object that implements interface <tt>Observer</tt>. After an
* observable instance changes, an application calling the
* <code>Observable</code>'s <code>notifyObservers</code> method
* causes all of its observers to be notified of the change by a call
* to their <code>update</code> method.
* <p>
* The order in which notifications will be delivered is unspecified.
* The default implementation provided in the Observable class will
* notify Observers in the order in which they registered interest, but
* subclasses may change this order, use no guaranteed order, deliver
* notifications on separate threads, or may guarantee that their
* subclass follows this order, as they choose.
* <p>
* Note that this notification mechanism has nothing to do with threads
* and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
* mechanism of class <tt>Object</tt>.
* <p>
* When an observable object is newly created, its set of observers is
* empty. Two observers are considered the same if and only if the
* <tt>equals</tt> method returns true for them.
*
* @author Chris Warth
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
* @see java.util.Observer
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
* @since JDK1.0
*/
public class Observable {
private boolean changed = false;
private Vector<Observer> obs; /** Construct an Observable with zero Observers. */ public Observable() {
obs = new Vector<>();
} /**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
} /**
* Deletes an observer from the set of observers of this object.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
} /**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to
* indicate that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and <code>null</code>. In other
* words, this method is equivalent to:
* <blockquote><tt>
* notifyObservers(null)</tt></blockquote>
*
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers() {
notifyObservers(null);
} /**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to indicate
* that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and the <code>arg</code> argument.
*
* @param arg any object.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal; synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
} for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
} /**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
} /**
* Marks this <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
protected synchronized void setChanged() {
changed = true;
} /**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
} /**
* Tests if this object has changed.
*
* @return <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
} /**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
5.举一个例子吧:当婴儿哭泣时,则通知家人来哄宝宝,那么这里很明显婴儿是一个被观察者,当婴儿哭泣时,立刻通知家人(观察者)
package com.bdqn.s2.javaoop.study.proxy; import java.lang.reflect.Proxy;
import java.util.Observable;
import java.util.Observer; /**
* 婴儿类,被观察者
*/
public class Baby extends Observable { private int hungry; private String name; public String getName() {
return name;
} public Baby(String name, int hungry) {
this.hungry = hungry;
this.name = name;
addObserver(new Parents());//添加观察者对象,需要家长监管
} /**
* 婴儿开始哭泣
*/
public void cry() {
if (hungry < 100) {
System.out.printf("baby%s饿了,开始哭泣...%n", name);
setChanged();//饥饿值过低,触发变化,此方法必须被调用
notifyObservers();//通知观察者
}
}
} /**
* 家长,观察者
*/
class Parents implements Observer {
@Override
public void update(Observable o, Object arg) { if (o instanceof Baby) {
Baby baby = (Baby) o;
System.out.println(baby.getName()+"开始哭泣,赶紧哄宝宝啦");
}
} } public class Main { public static void main(String[] args) {
Baby baby = new Baby("豆豆",9);
baby.cry();
}
} /*
输出结果
baby豆豆饿了,开始哭泣...
豆豆开始哭泣,赶紧哄宝宝啦
*/
二 关于动态代理模式
1)代理模式是设计模式中非常常见的一种模式,这种模式可以实现对原有方法的扩展,举个例子经纪人可以替明星们办理一些事情,那么此时经纪人可以视为明星的代理。
2)代理模式可以分为静态代理和动态代理,在这里我们只对JDK提供的动态代理进行讨论。
3)由于JDK提供的代理模式所代理的类继承了Proxy,因此我们只能接口进行代理,针对类的代理可以自行参考cglib框架
4)InvocationHandler:是代理实例的调用处理程序 实现的接口。 每个代理实例都具有一个关联的调用处理程序。对代理实例调用方法时,将对方法调用进行编码并将其指派到它的调用处理程序的 invoke
方法。
//proxy:代理类,method:代理执行的方法 args:方法参数
public Object invoke(Object proxy, Method method, Object[] args);
5)Proxy:该类主要是获取或者新创建动态代理对象
//该方法主要用于获取代理对象,注意一定是针对接口进行代理
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
6)针对上述例子进行改造:添加保姆类并改造Baby类的构造方法:
package com.bdqn.s2.javaoop.study.proxy; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Observer; /**
* 保姆类
*/
public class Nanny implements InvocationHandler { private Observer parents; public Nanny(){
parents = new Parents();
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("保姆开始照顾孩子");
Object object = method.invoke(parents, args);
return object;
}
}
Baby类构造函数改造:
public Baby(String name, int hungry) {
this.hungry = hungry;
this.name = name;
addObserver((Observer) Proxy.newProxyInstance(Baby.class.getClassLoader(),new Class[]{Observer.class},new Nanny()));
}
输出结果:
baby豆豆饿了,开始哭泣...
保姆开始照顾孩子
豆豆开始哭泣,赶紧哄宝宝啦
浅谈java中内置的观察者模式与动态代理的实现的更多相关文章
- 浅谈Java中set.map.List的区别
就学习经验,浅谈Java中的Set,List,Map的区别,对JAVA的集合的理解是想对于数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),JAVA集合可以存储和操 ...
- Java基础学习总结(29)——浅谈Java中的Set、List、Map的区别
就学习经验,浅谈Java中的Set,List,Map的区别,对JAVA的集合的理解是想对于数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),JAVA集合可以存储和操 ...
- 浅谈Java中的final关键字
浅谈Java中的final关键字 谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来 ...
- 浅谈Java中的equals和==(转)
浅谈Java中的equals和== 在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String("hello"); 2 String str ...
- 浅谈Java中的对象和引用
浅谈Java中的对象和对象引用 在Java中,有一组名词经常一起出现,它们就是“对象和对象引用”,很多朋友在初学Java的时候可能经常会混淆这2个概念,觉得它们是一回事,事实上则不然.今天我们就来一起 ...
- 浅谈Java中的equals和==
浅谈Java中的equals和== 在初学Java时,可能会经常碰到下面的代码: String str1 = new String("hello"); String str2 = ...
- 浅谈Java中的深拷贝和浅拷贝(转载)
浅谈Java中的深拷贝和浅拷贝(转载) 原文链接: http://blog.csdn.net/tounaobun/article/details/8491392 假如说你想复制一个简单变量.很简单: ...
- 浅谈Java中的深拷贝和浅拷贝
转载: 浅谈Java中的深拷贝和浅拷贝 假如说你想复制一个简单变量.很简单: int apples = 5; int pears = apples; 不仅仅是int类型,其它七种原始数据类型(bool ...
- 【转】浅谈Java中的hashcode方法(这个demo可以多看看)
浅谈Java中的hashcode方法 哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率.在Java的Object类中有一个方法: public native i ...
随机推荐
- RAID6三块硬盘离线导致的数据丢失恢复过程
小编我最近参与了一例非常成功的数据恢复的案例,在这里分享给大家.用户是一组6块750G磁盘的 RAID6,先后有两块磁盘离线,但维护人员在此情况下依然没有更换磁盘,所以在第三块硬盘离线后raid直接崩 ...
- js解决IE8不支持html5,css3的问题(respond.js 的使用注意)
IE8.0及以下不支持html5,css3的解析.目前为止IE8以下的版本使用率在10%左右,网站还是有必要兼容的. 1,在你的所有css最后判断引入两个js文件. html5.js 是用来让ie8 ...
- Hey,man,are you ok? -- 关于心跳、故障监测、lease机制
电话之于短信.微信的一个很大的不同点在于,前者更加及时,有更快速直接的反馈:而后面两个虽然称之为instant message,但经常时发出去了就得等对方回复,等多久是不确定的.打电话能明确知道对方在 ...
- Python内置函数(7)——sum
英文文档: sum(iterable[, start]) Sums start and the items of an iterable from left to right and returns ...
- [UWP] Custom Capability的使用
Custom Capability 是uwp开发中普通开发者较为不常用的内容,但是在一些OEM和驱动厂商,使用频率比较高 Custom Capability 有两种用户: 1.普通应用程序开发者: 2 ...
- sql优化基础篇
优化的步骤: 0.先sql运行看看是否真的很慢,注意设置SQL_NO_CACHE 1.where条件单表查,锁定最小返回记录表.这句话的意思是把查询语句的where都应用到表中返回的记录数最小的表开始 ...
- Nginx负载均衡(架构之路)
[前言] 在大型网站中,负载均衡是有想当必要的.尤其是在同一时间访问量比较大的大型网站,例如网上商城,新闻等CMS系统,为了减轻单个服务器的处理压力,我们引进了负载均衡这一个概念,将一个服务器的压力分 ...
- [LuoguP1113] 杂物 - 拓扑排序
其实只是纪念下第一篇洛谷题解? Description John的农场在给奶牛挤奶前有很多杂务要完成,每一项杂务都需要一定的时间来完成它.比如:他们要将奶牛集合起来,将他们赶进牛棚,为奶牛清洗乳房以及 ...
- 算法 排序NB二人组 堆排序 归并排序
参考博客:基于python的七种经典排序算法 常用排序算法总结(一) 序前传 - 树与二叉树 树是一种很常见的非线性的数据结构,称为树形结构,简称树.所谓数据结构就是一组数据的集合连同它们的储 ...
- AOV网络和Kahn算法拓扑排序
1.AOV与DAG 活动网络可以用来描述生产计划.施工过程.生产流程.程序流程等工程中各子工程的安排问题. 一般一个工程可以分成若干个子工程,这些子工程称为活动(Activity).完成了这些活动 ...