设计模式-观察者模式

package test.observer;

public interface BankObserver {
    public void update(double amt);
}
package test.observer;

/**
 * 银行客户
 * @author lenovo
 *
 */
public class CustomerBank1 implements BankObserver{
    private String email;
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    
    

    @Override
    public void update(double amt) {
        System.out.println("账户金额发生变动,发送邮件到"+email+",变动后金额为:"+amt);
    }
}
package test.observer;

public class CustomerBank2 implements BankObserver{
    private String phone;
    
    public String getPhone() {
        return phone;
    }
    
    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public void update(double amt) {
        System.out.println("账户金额发生变动,发送短信到"+phone+",变动后金额为:"+amt);
    }
    
}
package test.observer;

/**
 * 银行客户
 * @author lenovo
 *
 */
public class CustomerBank3 implements BankObserver{
    private String qq;
    
     
    
    

    public String getQq() {
        return qq;
    }





    public void setQq(String qq) {
        this.qq = qq;
    }





    @Override
    public void update(double amt) {
        System.out.println("账户金额发生变动,发送信息到qq:"+qq+",变动后金额为:"+amt);
    }
}
package test.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 银行账户
 * @author lenovo
 *
 */
public class BankAccount {
    private String name;
    private double amt;
    private List<BankObserver> list=new ArrayList<BankObserver>();
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getAmt() {
        return amt;
    }
    
    public void add(BankObserver obj){
        list.add(obj);
    }
    
    public void remove(BankObserver obj){
        list.remove(obj);
    }
    
    public void setAmt(double amt) {
        this.amt = amt;
        for(int i=0;i<list.size();i++){
            BankObserver bo=list.get(i);
            bo.update(amt);
        }
    }

}
package test.observer;

/**
 * 客户端
 * @author lenovo
 *
 */
public class Client {
    public static void main(String[] argv){
        /**
         * 银行发钱1000块工资,通知到银行客户的邮件
         */
        BankAccount bankAccount=new BankAccount();
        
        CustomerBank1 cb=new CustomerBank1();
        cb.setEmail("**********@qq.com");
        bankAccount.add(cb);
        
        
        CustomerBank2 cb2=new CustomerBank2();
        cb2.setPhone("00000000000000");
        bankAccount.add(cb2);
        
        CustomerBank3 cb3=new CustomerBank3();
        cb3.setQq("00000000000000");
        
        bankAccount.add(cb3);
        
        bankAccount.setAmt(1000);
    }
}

 

posted on 2016-08-21 12:09  悄悄的来,匆匆的走  阅读(152)  评论(0编辑  收藏  举报

导航