observer

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package observer;

import java.util.ArrayList;

/**
 * 观察者
 * @author lvxda
 */
public class Cat implements Subject{
    private String name;//猫的称呼
    private ArrayList<Observer> observers = new ArrayList<Observer>(); //被观察者注册到名单中

    public Cat(String name){
        this.name = name;
    }

    public void aim(Observer obs) {
        this.observers.add(obs);
    }

    //当观察者事件触发时,要通知被观察者,被观察者作出必要的反应
    public void cry(){
        System.out.println(name + " 大吼一声: 那里跑?");
        for(Observer obs : observers){
            obs.response();
        }
    }
}

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package observer;

/**
 * 被观察者
 * @author lvxda
 */
public class Master implements Observer {
    private Subject subject;

    public Master(Subject sub){
        this.subject = sub;
        subject.aim(this);
    }

    Master(String string) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    public void response() {
        System.out.println("女主人惊醒.....");
    }

}

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package observer;

import com.sun.org.apache.xpath.internal.axes.SubContextList;

/**
 * 被观察者
 * @author lvxda
 */
public class Mouse implements Observer{
    private String name;//名称
    private Subject subject;

    public Mouse(String name, Subject subject){
        this.name = name;
        this.subject = subject;
        subject.aim(this);
    }

    public void response() {
        System.out.println(name + " 撒丫子就跑......");
    }

}

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package observer;

/**
 *
 * @author lvxda
 */
public interface Observer {
    void response();
}

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.

 

 


 */

package observer;

/**
 *
 * @author lvxda
 */
public interface Subject {
    void aim(Observer obs);
}

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package observer;

/**
 *
 * @author lvxda
 */
public class Test {
    public  static void main(String[] args){
        //创建猫对象,花花
        Cat cat = new Cat("花花");

        //创建女主人对象
        Master master = new Master(cat);

        //创建两个老鼠对象
        Mouse m1 = new Mouse("大白",cat);
        Mouse m2 = new Mouse("小白", cat);

        //当花花发现大白和小白时候,他大吼一声
        cat.cry();
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值