---
title: "An design pattern of queue in bank"
author: "thinkingmt"
date: "2011-05-18T00:34:18Z"
tags: []
categories: ["编程语言"]
slug: "an-design-pattern-of-queue-in-bank"
draft: false
lastmod: "2011-05-24T09:03:34Z"
id: 1047791
url: "https://thinkingmt.iteye.com/blog/1047791"
---

这个学期的Course Work 选择了“银行排队模拟系统”这个题目， 用这学期新学的‘动词名词分析法’一想，感觉挺简单的。因为唯一一个核心的类---windows，在里边封装好处理客户的算法；再加上一个customer类，用ArrayList将其封装，按照固定顺序，传递给windows进行处理，整个程序就完成了；还有涵盖最大的类---bank，对windows类和ArrayList&lt;Customer&gt;进行封装。

 

最初的设计是这样的：用bank类监控windows类，每当windows空闲下来时候，分配给其任务（这样的话，windows需要一个isIdle的属性，来记录其空闲状态，每次isIdle发生改变，触发bank类的update()方法，进行分配任务，也就是将ArrayList&lt;Customer&gt;的最新一个元素传递给windows）。这样的设计模式，通过Observer&Observable的配合很好地模拟了这个系统，也很符合实际。

 

简明的代码示例如下：

 

```
public class windows extends Obervable
{
private isIdle;

public windows
{
isIdle = true;// default is open !
}

public void handleCustomer(Customer cus)
{
setIdle();//when handle a customer, the attribute 'isIdle' change from 'true' to 'false'
// code to handle a customer
setIdle();//when handle finished, the attribute 'isIdle' change from 'false' to 'true'
}

public void setIdle
{
if(isIdle == true)
{
isIdle = false;
setChanged();
notifyObservers();
}
if(isIdle == false)
{
isIdle = true;
setChanged();
notifyObservers();
}

}
}
```

 

 

 接下来，简示bank类的代码：

 

```
public class band implements Observer
{
private windows[] win = new windows[n];

private ArrayList[Customer] queue = new ArrayList<Customer>();

public bank()
{
//some private method to initilize some parameter,like 'win' and 'queue'

private initWin();

private initQueue();

// the above private method is not very necessary to show,cause it's not attribute to illustrate the design pattern in this program, so do not show in this class.

}

public void update(Observable obs, Object arg)
{
//Because bank is an observer of windows, so in this method, 'obs' is a object of windows, arg is null, because the method notifyObservers() contains no parameter.

obs.handleCustomer(queue.offer());// assign the oldest customer in arraylist(cause the oldest means stand in the front of queue.)
}
}
```

 

   上面俩个类的代码，只能表示我本人对这个程序设计模式的思路，真正能运行的代码，在这里并不给出，因为真正做的时候，需要考虑到许多其他问题（比如，每一个窗口都需用一个独立的线程（thread），但由于我对线程的了解也并不多，所以在这里略去不说了，相信对线程了解多的大虾，可以轻松为此程序；此外，设计线程对于arraylist的操作，必须要同步synchronized，否则整个程序杂乱无章，根本达不到银行排队的效果，可能会出现多个窗口同时处理一个顾客的现实生活不可能发生的状况）。所以上述代码，仅仅是我的这个程序的design pattern(用到了Observable & Observer),和Logical path。

 

供大家参考而已，希望大虾可以指点，赐教！