|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
给某个对象一个设置一个观察者,以便能敏感捕获到对象的变化 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); } } 返回类别: 教程 上一教程: SPRING 编程入门十大问题解答 下一教程: JSP实践要点 您可以阅读与"OBSERVER模式"相关的教程: · MVC-OBSERVER模式 · 利用Observer模式解决组件间通信问题 · [java技术] 2.23 J2EE开发模式说明 · jsp设计模式 · Draw2D--1. 设计思想和相关模式 |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |