观察者模式java代码 java 观察者模式 流程审批
JAVA观察者模式(observer pattern)
import java.util.ArrayList;
成都创新互联从2013年创立,是专业互联网技术服务公司,拥有项目成都做网站、网站设计网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元普兰做网站,已为上家服务,为普兰各地企业和个人服务,联系电话:18980820575
import java.util.HashMap;
import java.util.Random;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class StockLists implements Runnable
{
private HashMapString, Stock hmStocks = new HashMapString, Stock();
private HashMapString, ArrayListChangeListener hmCL = new HashMapString, ArrayListChangeListener();
public StockLists()
{
init(100);
new Thread(this).start();
}
public void run()
{
Random rand = new Random();
while (true)
{
try
{
Thread.sleep(100);
Stock s = randStock();
s.price = rand.nextFloat();
ArrayListChangeListener alCL = hmCL.get(s.symbol);
if (alCL == null)
{
continue;
}
for (ChangeListener cl : alCL)
{
cl.stateChanged(new ChangeEvent(s));
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
private Stock randStock()
{
Random rand = new Random();
int idx = rand.nextInt(hmStocks.size());
String sym = (String) hmStocks.keySet().toArray()[idx];
Stock s = hmStocks.get(sym);
return s;
}
public boolean addChangeListener(ChangeListener cl, String sym)
{
ArrayListChangeListener al = hmCL.get(sym);
if (al == null)
{
al = new ArrayListChangeListener();
hmCL.put(sym, al);
}
return al.add(cl);
}
private void init(int count)
{
Random rand = new Random();
for (int i = 0; i count; i++)
{
String sym = randSym(rand);
float p = rand.nextFloat();
Stock s = new Stock(sym, p);
hmStocks.put(sym, s);
}
}
private String randSym(Random rand)
{
char[] ca = new char[3];
for (int i = 0; i ca.length; i++)
{
ca[i] = (char) ('A' + rand.nextInt(26));
}
return new String(ca);
}
public static void main(String[] args)
{
StockLists sl = new StockLists();
sl.addChangeListener(new Investor("111"), sl.randStock().symbol);
sl.addChangeListener(new Investor("222"), sl.randStock().symbol);
sl.addChangeListener(new Investor("333"), sl.randStock().symbol);
sl.addChangeListener(new Investor("444"), sl.randStock().symbol);
sl.addChangeListener(new Investor("555"), sl.randStock().symbol);
sl.addChangeListener(new Investor("666"), sl.randStock().symbol);
sl.addChangeListener(new Investor("777"), sl.randStock().symbol);
sl.addChangeListener(new Investor("888"), sl.randStock().symbol);
sl.addChangeListener(new Investor("999"), sl.randStock().symbol);
sl.addChangeListener(new Investor("000"), sl.randStock().symbol);
}
}
class Stock
{
public String symbol = null;
public float price = 0.0f;
public Stock(String sym, float p)
{
symbol = sym;
price = p;
}
public String toString()
{
return symbol + ":" + price;
}
}
class Investor implements ChangeListener
{
public String name = "";
public Investor(String name)
{
this.name = name;
}
@Override
public void stateChanged(ChangeEvent e)
{
Stock s = (Stock) e.getSource();
System.out.println("Hello," + name + " : STOCK CHANGED: " + s);
}
}
java 设计模式之 观察者模式(Observer)
//Subject java
package youngmaster model Observer;
/**
* @author youngmaster
* @E mail:young * @version myEclipse
* @create time 上午 : :
*/
/**
* 察者模式属于行为型模式 其意图是定义对象间的一种一对多的依赖关系
* 当一个对象的状态发生改变时 所有依赖于它的对象都得到通知并被自动更新
* 在制作系统的过程中 将一个系统分割成一系列相互协作的类有一个常见的副作用
* 需要维护相关对象间的一致性 我们不希望为了维持一致性而使各类紧密耦合
* 因为这样降低了他们的可充用性 这一个模式的关键对象是目标(Subject)和观察者(Observer)
* 一个目标可以有任意数目的依赖它的观察者 一旦目标的状态发生改变 所有的观察者都得到通知
* 作为对这个通知的响应 每个观察者都将查询目标以使其状态与目标的状态同步 这种交互也称为发布 订阅模式
* 目标是通知的发布者 他发出通知时并不需要知道谁是他的观察者 可以有任意数据的观察者订阅并接收通知
*/
/**
* subject
*目标接口
*/
public interface Subject {
public void addObserver(Observer o);
public void deletObserver(Observer o);
public void notice();
}
//Observer java
package youngmaster model Observer;
/**
* @author youngmaster
* @E mail:young * @version myEclipse
* @create time 上午 : :
*/
/**
*观察者接口
*/
public interface Observer {
public void update();
}
//Teacher java
package youngmaster model Observer;
import java util Vector;
/**
* @author youngmaster
* @E mail:young * @version myEclipse
* @create time 上午 : :
*/
/**
*目标接口实现
*/
public class Teacher implements Subject {
private String phone;
@SuppressWarnings( unchecked )
private Vector students;
@SuppressWarnings( unchecked )
public Teacher() {
phone = ;
students = new Vector();
}
@SuppressWarnings( unchecked )
@Override
public void addObserver(Observer o) {
students add(o);
}
@Override
public void deletObserver(Observer o) {
students remove(o);
}
@Override
public void notice() {
for (int i = ; i students size(); i++) { ((Observer) students get(i)) update();
}
}
public void setPhone(String phone) {
this phone = phone;
notice();
}
public String getPhone() {
return phone;
}
}
//Student java
package youngmaster model Observer;
/**
* @author youngmaster
* @E mail:young * @version myEclipse
* @create time 上午 : :
*/
/**
*观察者接口实现
*/
public class Student implements Observer {
private String name;
private String phone;
private Teacher teacher;
public Student(String name Teacher teacher) { this name = name; this teacher = teacher;
}
public void show() {
System out println( Name: + name + \nTeacher s phone: + phone);
}
@Override
public void update() {
phone = teacher getPhone();
}
}
//Client java
package youngmaster model Observer;
import java util Vector;
/**
* @author youngmaster
* @E mail:young * @version myEclipse
* @create time 上午 : :
*/
/**
*测试类
*/
public class Client {
/**
* @param args
*/
@SuppressWarnings( unchecked )
public static void main(String[] args) {
Vector students = new Vector();
Teacher teacher = new Teacher();
for (int i = ; i ; i++) {
Student student = new Student( student + i teacher); students add(student); teacher addObserver(student);
}
teacher setPhone( );
for (int i = ; i ; i++)
((Student) students get(i)) show();
System out println( \n============================\n );
teacher setPhone( );
for (int i = ; i ; i++)
((Student) students get(i)) show();
}
lishixinzhi/Article/program/Java/gj/201311/27566
Java中使用观察者模式实现自定义事件
MyEventTest java:
package wintys event;
import javax swing event EventListenerList;
import java util Date;
import java text DateFormat;
import java text SimpleDateFormat;
/**
* Java的事件机制/自定义事件
运行结果:
do something interesting in source here
listener detects [event]:wintys event MyEvent[source=wintys event MySource@
] [occur at]: : :
listener detects [event]:wintys event MyEvent[source=wintys event MySource@
] [occur at]: : :
* @version
* @author 天堂露珠 ()
* @see
*/
class MyEventTest{
public static void main(String[] args){
MySource source = new MySource();
MyListener myListener = new MyListener(){
public void doMyAction(MyEvent e){
System out println( listener detects + e);
}
};
source addMyListener(myListener);
source addMyListener(myListener);
source addMyListener(myListener);
source removeMyListener(myListener);
source doSomething();
}
}
/**
* 自定义的事件
* @version
* @author 天堂露珠()
* @see
*/
class MyEvent extends java util EventObject{
private Date date;//记录事件发生的时间
public MyEvent(Object source Date date){
super(source);
this date = date;
}
public String toString(){
DateFormat df = new SimpleDateFormat( yyyy MM dd HH:mm:ss );
String dt = df format(date);
return [event]: + super toString() + [occur at]: + dt;
}
}
/**
* 自定义事件监听器接口
* @version
* @author 天堂露珠()
* @see
*/
interface MyListener extends java util EventListener{
void doMyAction(MyEvent e);
}
/**
* 自定义事件源
* @version
* @author 天堂露珠()
* @see
*/
class MySource{
/**
* 保存注册的监听器列表
* 子类可以使用它保存自己的事件监听器(非MyListener监听器)列表
*/
protected EventListenerList listenerList = new EventListenerList();
private MyEvent myEvent = null;//fireDoMyAction()使用此变量
/**
* 没有做任何事
*/
public MySource(){
}
/**
* 添加一个MyListener监听器
*/
public void addMyListener(MyListener listener){
listenerList add(MyListener class listener);
}
/**
* 移除一个已注册的MyListener监听器
* 如果监听器列表中已有相同的监听器listener listener
* 并且listener ==listener
* 那么只移除最近注册的一个监听器
*/
public void removeMyListener(MyListener listener){
listenerList remove(MyListener class listener);
}
/**
* @return 在此对象上监听的所有MyListener类型的监听器
*/
public MyListener[] getMyListeners(){
return (MyListener[])listenerList getListeners(MyListener class);
}
//Winty:Copy directly from javax swing event EventListenerList
/*Notify all listeners that have registered interest for
notification on this event type The event instance
is lazily created using the parameters passed into
the fire method
*/
protected void fireDoMyAction() {
// getListenerList() Guaranteed to return a non null array
Object[] listeners = listenerList getListenerList();
// Process the listeners last to first notifying
// those that are interested in this event
for (int i = listeners length ; i= ; i = ) {
if (listeners[i]==MyListener class) {
// Lazily create the event:
if (myEvent == null)
myEvent = new MyEvent(this new Date());
((MyListener)listeners[i+ ]) doMyAction(myEvent);
}
}
}
/**
* 做一些事件源应该做的有意义的事 然后通知监听器
* 这里只是一个示例方法
* 例如:MySource如果是一个按钮 则doSomething()就可以命名为click()
* 当用户点击按钮时调用click()方法
*/
public void doSomething() {
System out println( do something interesting here );
fireDoMyAction();//通知监听器
}
}
lishixinzhi/Article/program/Java/hx/201311/26237
当前题目:观察者模式java代码 java 观察者模式 流程审批
文章起源:http://scjbc.cn/article/dosecic.html