重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
第一个
专注于为中小企业提供成都网站制作、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业海南州免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了超过千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
public interface RandomNumberListener {//接口
public void numberChanged(double d);
}
第二个
public class Consol implements RandomNumberListener{
@Override
public void numberChanged(double d) {
System.out.println(d);
}
}
第三个
public class SwingWindow
extends JFrame
implements RandomNumberListener{//观察者
private JLabel label = new JLabel();
public SwingWindow(){
this.getContentPane().add( label);
this.setSize(300,200);
this.setVisible(true);
}
@Override
public void numberChanged(double d) {
label.setText(String.valueOf(d));
}
}
第四个
public class RandomNumber {//业务
private double r;
private ListRandomNumberListener listeners = new ArrayListRandomNumberListener();
//添加所有观察者
public void addRandomNumberListener(RandomNumberListener lis){
listeners.add(lis);
}
public void random(){
r = Math.random();
//数据发生改变,通知所有的观察者
for (RandomNumberListener lis : listeners) {
lis.numberChanged(r);
}
}
}
第五个
public class Test {
public static void main(String[] args) throws InterruptedException{
RandomNumber rn = new RandomNumber();
SwingWindow sw = new SwingWindow();
Consol c = new Consol();
rn.addRandomNumberListener(sw);
rn.addRandomNumberListener(c);
while(true){
rn.random();
Thread.sleep(new Random().nextInt(3000)+1000L);
}
}
}
import java.util.ArrayList;
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);
}
}
package TestObserver;
import java.util.Iterator;
import java.util.Vector;
/**
*
* @author Seastar
*/
interface Observed {
public void addObserver(Observer o);
public void removeObserver(Observer o);
public void update();
}
interface Observer {
public void takeAction();
}
class Invoker {
private Observer o;
Handler handler;
public Invoker(Observer o) {
new Handler();
this.o = o;
}
private class Handler extends Thread {
public Handler() {
handler = this;
}
@Override
public void run() {
o.takeAction();
}
}
public boolean TestSameObserver(Observer o) {
return o == this.o;
}
public void invoke() {
handler.start();
}
}
class ObservedObject implements Observed {
private VectorInvoker observerList = new VectorInvoker();
public void addObserver(Observer o) {
observerList.add(new Invoker(o));
}
public void removeObserver(Observer o) {
IteratorInvoker it = observerList.iterator();
while (it.hasNext()) {
Invoker i = it.next();
if (i.TestSameObserver(o)) {
observerList.remove(i);
break;
}
}
}
public void update() {
for (Invoker i : observerList) {
i.invoke();
}
}
}
class ObserverA implements Observer {
public void takeAction() {
System.out.println("I am Observer A ,state changed ,so i have to do something");
}
}
class ObserverB implements Observer {
public void takeAction() {
System.out.println("I am Observer B ,i was told to do something");
}
}
class ObserverC implements Observer {
public void takeAction() {
System.out.println("I am Observer C ,I just look ,and do nothing");
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ObserverA a = new ObserverA();
ObserverB b = new ObserverB();
ObserverC c = new ObserverC();
ObservedObject oo = new ObservedObject();
oo.addObserver(a);
oo.addObserver(b);
oo.addObserver(c);
for (int i = 0; i 5; ++i) {
oo.addObserver(new Observer() {
public void takeAction() {
System.out.println("我是山寨观察者"+",谁敢拦我");
}
});
}
//sometime oo changed ,so it calls update and informs all observer
oo.update();
}
}
观察者模式的精髓在于注册一个观察者观测可能随时变化的对象,对象变化时就会自动通知观察者,
这样在被观测对象影响范围广,可能引起多个类的行为改变时很好用,因为无需修改被观测对象的代码就可以增加被观测对象影响的类,这样的设计模式使得代码易于管理和维护,并且减少了出错几率
至于异步机制实际是个噱头,可以有观测对象来实现异步,也可以有观察者自身实现,这个程序实际是观测对象实现了异步机制,方法是在观察者类外包装了一层invoker类