·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » OBSERVER模式

OBSERVER模式

类别: JSP教程  评论数:0 总得分:0
给某个对象一个设置一个观察者,以便能敏感捕捉到对象的变化
package observer;

import java.util.*;


public class Product extends Observable {
private String name;
private float price;
public String getName() {
return name;
}

public float getPrice() {
return price;
}

private int id;

public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers("name");
}
public void setPrice(float price) {
this.price = price;
setChanged();
notifyObservers("price");
//notifyObservers();
}
}
****************************************************************
package observer;

import java.util.*;

public class PriceObserver implements Observer {
private float price = 0;
public void update(Observable obj, Object arg) {

try{
if (arg instanceof String) {
String argName = (String)arg;
if(argName.trim().equalsIgnoreCase("price")){
int id = 0;
float price = 0;
String test = "";
if(obj instanceof Product){
Product pro = (Product)obj;
price = pro.getPrice();
id = pro.getId();
}

System.out.println("PriceObserver : Product "+id+" \'s pirce has changed to " + price);
}
}

}catch(Exception ex){
ex.printStackTrace();
}

}
}
*********************************************************************
package observer;

import java.util.*;
public class NameObserver implements Observer {
private String name = null;
public void update(Observable obj, Object arg) {
try{

if (arg instanceof String) {
String argName = (String)arg;
if(argName.trim().equalsIgnoreCase("name")){
int id = 0;
String name = "";
if(obj instanceof Product){
Product pro = (Product)obj;
name = pro.getName();
id = pro.getId();
}
System.out.println("NameObserver : Product "+id+" \'s name has changed to " + name);
}
}


}catch(Exception ex){
ex.printStackTrace();
}
}
}
*********************************************************************
package observer;

public class Main {
public static void main(String args[]) {
Product product = new Product(1,"桔子",(float)9.20);
//Product product = new Product();
NameObserver nameobs = new NameObserver();
PriceObserver priceobs = new PriceObserver();
product.addObserver(nameobs);
product.addObserver(priceobs);
product.setName("苹果");
product.setPrice(12.80f);
product.setName("香蕉");
product.setPrice(6.00f);
}
}
-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1