---------------------- android培训、java培训、期待与您交流! ------------------------
银行的排号机是个司空见惯的机器,开始学习java之后就在思考如何用面向对象的思想来解决它
但是思考很长时间都没有实现,今天在视频中看到老师的精彩实现,真的很漂亮
抄在下面作为笔记:
这是取号码机器
public class NumberMachine {
private NumberMachine(){}
private static NumberMachine instance = new NumberMachine();
public static NumberMachine getInstance(){
return instance;
}
private NumberManager commonManager = new NumberManager();
private NumberManager expressManager = new NumberManager();
private NumberManager vipManager = new NumberManager();
public NumberManager getCommonManager() {
return commonManager;
}
public NumberManager getExpressManager() {
return expressManager;
}
public NumberManager getVipManager() {
return vipManager;
}
}
下面是号码生成器,用的数据结构其实很简单,就是一个队列,先进先出的队列
而这个队列的实现使用一个链表list
import java.util.ArrayList;
import java.util.List;
public class NumberManager {
private int lastNumber = 0;
private List queueNumbers = new ArrayList();
public synchronized Integer generateNewNumber(){
queueNumbers.add(++lastNumber);
return lastNumber;
}
public synchronized Integer fetchNumber(){
if(queueNumbers.size()>0){
return (Integer)queueNumbers.remove(0);
}else{
return null;
}
}
}
---------------------- android培训、java培训、期待与您交流! ------------------------