一、实验目的
(1)理解行为型设计模式基本概念
(2)掌握主要的行为型设计模式
二、实验内容1
-
问题描述
策略模式 -
软件设计
-
程序实现代码
ArrayHandler.java
public class ArrayHandler
{
private Sort sortObj;
public int[] sort(int arr[])
{
sortObj.sort(arr);
return arr;
}
public void setSortObj(Sort sortObj) {
this.sortObj = sortObj;
}
}
BubbleSort.java
public class BubbleSort implements Sort
{
public int[] sort(int arr[])
{
int len=arr.length;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
int temp;
if(arr[i]>arr[j])
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
System.out.println("冒泡排序");
return arr;
}
}
Client.java
public class Client
{
public static void main(String args[])
{
int arr[]={1,4,6,2,5,3,7,10,9};
int result[];
ArrayHandler ah=new ArrayHandler();
Sort sort;
sort=(Sort)XMLUtil.getBean();
ah.setSortObj(sort); //设置具体策略
result=ah.sort(arr);
for(int i=0;i<result.length;i++)
{
System.out.print(result[i] + ",");
}
}
}
config.xml
<?xml version="1.0"?>
<config>
<className>QuickSort</className>
</config>
InsertionSort.java
public class InsertionSort implements Sort
{
public int[] sort(int arr[])
{
int len=arr.length;
for(int i=1;i<len;i++)
{
int j;
int temp=arr[i];
for(j=i;j>0;j--)
{
if(arr[j-1]>temp)
{
arr[j]=arr[j-1];
}else
break;
}
arr[j]=temp;
}
System.out.println("插入排序");
return arr;
}
}
QuickSort.java
public class QuickSort implements Sort
{
public int[] sort(int arr[])
{
System.out.println("快速排序");
sort(arr,0,arr.length-1);
return arr;
}
public void sort(int arr[],int p, int r)
{
int q=0;
if(p<r)
{
q=partition(arr,p,r);
sort(arr,p,q-1);
sort(arr,q+1,r);
}
}
public int partition(int[] a, int p, int r)
{
int x=a[r];
int j=p-1;
for(int i=p;i<=r-1;i++)
{
if(a[i]<=x)
{
j++;
swap(a,j,i);
}
}
swap(a,j+1,r);
return j+1;
}
public void swap(int[] a, int i, int j)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
SelectionSort.java
public class SelectionSort implements Sort
{
public int[] sort(int arr[])
{
int len=arr.length;
int temp;
for(int i=0;i<len;i++)
{
temp=arr[i];
int j;
int samllestLocation=i;
for(j=i+1;j<len;j++)
{
if(arr[j]<temp)
{
temp=arr[j];
samllestLocation=j;
}
}
arr[samllestLocation]=arr[i];
arr[i]=temp;
}
System.out.println("选择排序");
return arr;
}
}
Sort.java
public interface Sort
{
public abstract int[] sort(int arr[]);
}
XMLUtil.java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtil
{
//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象
public static Object getBean()
{
try
{
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("config.xml"));
//获取包含类名的文本节点
NodeList nl = doc.getElementsByTagName("className");
Node classNode=nl.item(0).getFirstChild();
String cName=classNode.getNodeValue();
//通过类名生成实例对象并将其返回
Class c=Class.forName(cName);
Object obj=c.newInstance();
return obj;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
- 测试及运行结果
三、实验内容2
-
问题描述
访问者模式 -
软件设计
-
程序实现代码
Apple.java
public class Apple implements Product
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}
Book.java
public class Book implements Product
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}
BuyBasket.java
import java.util.*;
public class BuyBasket
{
private ArrayList list=new ArrayList();
public void accept(Visitor visitor)
{
Iterator i=list.iterator();
while(i.hasNext())
{
((Product)i.next()).accept(visitor);
}
}
public void addProduct(Product product)
{
list.add(product);
}
public void removeProduct(Product product)
{
list.remove(product);
}
}
Client.java
public class Client
{
public static void main(String a[])
{
Product b1=new Book();
Product b2=new Book();
Product a1=new Apple();
Visitor visitor;
BuyBasket basket=new BuyBasket();
basket.addProduct(b1);
basket.addProduct(b2);
basket.addProduct(a1);
visitor=(Visitor)XMLUtil.getBean();
visitor.setName("张三");
basket.accept(visitor);
}
}
config.xml
<?xml version="1.0"?>
<config>
<className>Saler</className>
</config>
Customer.java
public class Customer extends Visitor
{
public void visit(Apple apple)
{
System.out.println("顾客" + name + "选苹果。");
}
public void visit(Book book)
{
System.out.println("顾客" + name + "买书。");
}
}
Product.java
public interface Product
{
void accept(Visitor visitor);
}
Saler.java
public class Saler extends Visitor
{
public void visit(Apple apple)
{
System.out.println("收银员" + name + "给苹果过秤,然后计算其价格。");
}
public void visit(Book book)
{
System.out.println("收银员" + name + "直接计算书的价格。");
}
}
Visitor.java
public abstract class Visitor
{
protected String name;
public void setName(String name)
{
this.name=name;
}
public abstract void visit(Apple apple);
public abstract void visit(Book book);
}
XMLUtil.java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtil
{
//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象
public static Object getBean()
{
try
{
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("config.xml"));
//获取包含类名的文本节点
NodeList nl = doc.getElementsByTagName("className");
Node classNode=nl.item(0).getFirstChild();
String cName=classNode.getNodeValue();
//通过类名生成实例对象并将其返回
Class c=Class.forName(cName);
Object obj=c.newInstance();
return obj;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
- 测试及运行结果
四、实验内容3
-
问题描述
状态模式 -
软件设计
-
程序实现代码
AbstractState.java
public abstract class AbstractState
{
protected ForumAccount acc;
protected int point;
protected String stateName;
public abstract void checkState(int score);
public void downloadFile(int score)
{
System.out.println(acc.getName() + "下载文件,扣除" + score + "积分。");
this.point-=score;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。");
}
public void writeNote(int score)
{
System.out.println(acc.getName() + "发布留言" + ",增加" + score + "积分。");
this.point+=score;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。");
}
public void replyNote(int score)
{
System.out.println(acc.getName() + "回复留言,增加" + score + "积分。");
this.point+=score;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。");
}
public void setPoint(int point) {
this.point = point;
}
public int getPoint() {
return (this.point);
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getStateName() {
return (this.stateName);
}
}
Client.java
public class Client
{
public static void main(String args[])
{
ForumAccount account=new ForumAccount("张三");
account.writeNote(20);
System.out.println("--------------------------------------");
account.downloadFile(20);
System.out.println("--------------------------------------");
account.replyNote(100);
System.out.println("--------------------------------------");
account.writeNote(40);
System.out.println("--------------------------------------");
account.downloadFile(80);
System.out.println("--------------------------------------");
account.downloadFile(150);
System.out.println("--------------------------------------");
account.writeNote(1000);
System.out.println("--------------------------------------");
account.downloadFile(80);
System.out.println("--------------------------------------");
}
}
ForumAccount.java
public class ForumAccount
{
private AbstractState state;
private String name;
public ForumAccount(String name)
{
this.name=name;
this.state=new PrimaryState(this);
System.out.println(this.name + "注册成功!");
System.out.println("---------------------------------------------");
}
public void setState(AbstractState state)
{
this.state=state;
}
public AbstractState getState()
{
return this.state;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
public void downloadFile(int score)
{
state.downloadFile(score);
}
public void writeNote(int score)
{
state.writeNote(score);
}
public void replyNote(int score)
{
state.replyNote(score);
}
}
HighState.java
public class HighState extends AbstractState
{
public HighState(AbstractState state)
{
this.acc=state.acc;
this.point=state.getPoint();
this.stateName="专家";
}
public void writeNote(int score)
{
System.out.println(acc.getName() + "发布留言" + ",增加" + score + "*2个积分。");
this.point+=score*2;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。");
}
public void downloadFile(int score)
{
System.out.println(acc.getName() + "下载文件,扣除" + score + "/2积分。");
this.point-=score/2;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。"); }
public void checkState(int score)
{
if(point<0)
{
System.out.println("余额不足,文件下载失败!");
this.point+=score;
}
else if(point<=100)
{
acc.setState(new PrimaryState(this));
}
else if(point<=1000)
{
acc.setState(new MiddleState(this));
}
}
}
MiddleState.java
public class MiddleState extends AbstractState
{
public MiddleState(AbstractState state)
{
this.acc=state.acc;
this.point=state.getPoint();
this.stateName="高手";
}
public void writeNote(int score)
{
System.out.println(acc.getName() + "发布留言" + ",增加" + score + "*2个积分。");
this.point+=score*2;
checkState(score);
System.out.println("剩余积分为:" + this.point + ",当前级别为:" + acc.getState().stateName + "。");
}
public void checkState(int score)
{
if(point>=1000)
{
acc.setState(new HighState(this));
}
else if(point<0)
{
System.out.println("余额不足,文件下载失败!");
this.point+=score;
}
else if(point<=100)
{
acc.setState(new PrimaryState(this));
}
}
}
PrimaryState.java
public class PrimaryState extends AbstractState
{
public PrimaryState(AbstractState state)
{
this.acc=state.acc;
this.point=state.getPoint();
this.stateName="新手";
}
public PrimaryState(ForumAccount acc)
{
this.point=0;
this.acc=acc;
this.stateName="新手";
}
public void downloadFile(int score)
{
System.out.println("对不起," + acc.getName() + ",您没有下载文件的权限!");
}
public void checkState(int score)
{
if(point>=1000)
{
acc.setState(new HighState(this));
}
else if(point>=100)
{
acc.setState(new MiddleState(this));
}
}
}
- 测试及运行结果
五、实验内容4
-
问题描述
观察者模式 -
软件设计
-
程序实现代码
LoginBean.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
//Concrete Subject
public class LoginBean extends JPanel implements ActionListener
{
private JLabel labUserName,labPassword;
private JTextField txtUserName;
private JPasswordField txtPassword;
private JButton btnLogin,btnClear;
private LoginEventListener lel; //Abstract Observer
private LoginEvent le;
public LoginBean()
{
this.setLayout(new GridLayout(3,2));
labUserName=new JLabel("User Name:");
add(labUserName);
txtUserName=new JTextField(20);
add(txtUserName);
labPassword=new JLabel("Password:");
add(labPassword);
txtPassword=new JPasswordField(20);
add(txtPassword);
btnLogin=new JButton("Login");
add(btnLogin);
btnClear=new JButton("Clear");
add(btnClear);
btnClear.addActionListener(this);
btnLogin.addActionListener(this);//As a concrete observer for another subject,ActionListener as the abstract observer.
}
//Add an observer.
public void addLoginEventListener(LoginEventListener lel)
{
this.lel=lel;
}
//private or protected as the notify method
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("");
}
}
}
LoginEvent.java
import java.util.EventObject;
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;
}
}
LoginEventListener.java
import java.util.EventListener;
//Abstract Observer
public interface LoginEventListener extends EventListener
{
public void validateLogin(LoginEvent event);
}
LoginValidatorA.java
import javax.swing.*;
import java.awt.*;
//Concrete Observer
public class LoginValidatorA extends JFrame implements LoginEventListener
{
private JPanel p;
private LoginBean lb;
private JLabel lblLogo;
public LoginValidatorA()
{
super("Bank of China");
p=new JPanel();
this.getContentPane().add(p);
lb=new LoginBean();
lb.addLoginEventListener(this);
Font f=new Font("Times New Roman",Font.BOLD,30);
lblLogo=new JLabel("Bank of China");
lblLogo.setFont(f);
lblLogo.setForeground(Color.red);
p.setLayout(new GridLayout(2,1));
p.add(lblLogo);
p.add(lb);
p.setBackground(Color.pink);
this.setSize(600,200);
this.setVisible(true);
}
public void validateLogin(LoginEvent event)
{
String userName=event.getUserName();
String password=event.getPassword();
if(0==userName.trim().length()||0==password.trim().length())
{
JOptionPane.showMessageDialog(this,new String("Username or Password is empty!"),"alert",JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(this,new String("Valid Login Info!"),"alert",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[])
{
new LoginValidatorA().setVisible(true);
}
}
LoginValidatorB.java
import javax.swing.*;
import java.awt.*;
public class LoginValidatorB extends JFrame implements LoginEventListener
{
private JPanel p;
private LoginBean lb;
private JLabel lblLogo;
public LoginValidatorB()
{
super("China Mobile");
p=new JPanel();
this.getContentPane().add(p);
lb=new LoginBean();
lb.addLoginEventListener(this);
Font f=new Font("Times New Roman",Font.BOLD,30);
lblLogo=new JLabel("China Mobile");
lblLogo.setFont(f);
lblLogo.setForeground(Color.blue);
p.setLayout(new GridLayout(2,1));
p.add(lblLogo);
p.add(lb);
p.setBackground(new Color(163,185,255));
this.setSize(600,200);
this.setVisible(true);
}
public void validateLogin(LoginEvent event)
{
String userName=event.getUserName();
String password=event.getPassword();
if(userName.equals(password))
{
JOptionPane.showMessageDialog(this,new String("Username must be different from password!"),"alert",JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(this,new String("Rigth details!"),"alert",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[])
{
new LoginValidatorB().setVisible(true);
}
}
- 测试及运行结果
总结