东南大学Java设计模式作业观察者模式

2019-01-12 15:41

实例一:猫、狗与老鼠

假设猫是老鼠和狗的观察目标,老鼠和狗是观察者,猫叫老鼠跑,狗也跟着叫,使用观察者模式描述该过程。

类图:

代码:

import java.util.*;

public abstract class MySubject {

protected ArrayList observers = new ArrayList(); public abstract void attach(MyObserver obs); public abstract void detach(MyObserver obs); public abstract void cry(); }public class Cat extends MySubject

{

public void attach(MyObserver obs) { obs.add(obs); }

public void detach(MyObserver obs) { obs.remove(obs); }

public void cry() { for(Object obs:obs) { ((MyObserver)obs).response(); } }

}

public interface MyObserver {

public void response(); }

public class Mouse {

public void response() { //具体更新代码 } }

public class Dog {

public void response() { //具体更新代码 } }

实例二:自定义登录控件

Java事件处理模型中应用了观察者模式,下面通过一个实例来学习如何自定义Java控件,并给该控件增加相应的事件。该实例基于Java Swing/AWT控件,在Swing/AWT的相关类中封装了对事件的底层处理。

类图:

代码:

import javax.swing.*; import java.awt.event.*; import java.awt.*;

import java.util.EventObject; import java.util.EventListener;

public class LoginBean extends JPanel implements ActionListener { private LoginEventListener lel; private LoginEvent le; public LoginBean() { //详细代码 } public void addLoginEventListener(LoginEventListener lel) { this.lel=lel;

} private void fireLoginEvent(Object object,String userName,String password) { le=new LoginEvent(btnLogin,userName,password); lel.validateLogin(le); } public void actionPerformed(ActionEvent event) { if(btnLogin==event.getSource()) { String userName=this.txtUserName.getText(); String password=this.txtPassword.getText(); fireLoginEvent(btnLogin,userName,password); } if(btnClear==event.getSource()) { this.txtUserName.setText(\ this.txtPassword.setText(\ } } }

public class LoginEvent extends EventObject { private String userName; private String password; public LoginEvent(Object source,String userName,String password) { super(source); this.userName=userName; this.password=password; } public void setUserName(String userName) { this.userName=userName; } public String getUserName()

{ return this.userName; } public void setPassword(String password) { this.password=password; } public String getPassword() { return this.password; } }

public interface LoginEventListener extends EventListener { public void validateLogin(LoginEvent event); }

public class LoginValidatorA extends JFrame implements LoginEventListener { private LoginBean lb; public LoginValidatorA() { super(\ p=new JPanel(); this.getContentPane().add(p); lb=new LoginBean(); lb.addLoginEventListener(this); } public void validateLogin(LoginEvent event) { //详细代码 } }

public class LoginValidatorB extends JFrame implements LoginEventListener { private LoginBean lb; public LoginValidatorB() { super(\


东南大学Java设计模式作业观察者模式.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:我学会了洗碗作文500字

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: