本帖最后由 静以修身 于 2013-8-18 19:46 编辑
张孝祥老师视频里说过下面的这部分代码可以进行优化,可以将commonService()函数内的那部分代码设计成一个抽象类,不确定的那部分(红色那部分代码),分别设计成两个抽象函数,假如第一部分红色代码提取为:getNumber()、第二部分红色代码提取为:notGetTask();让子类去复写。然后设计三个子类CommonService、ExpressService、VipService分别去实现它,当子类ExpressService在实现notGetTask()抽象函数的时候,要调用CommonService类中的功能,如何实现。求优化后的代码??
private void commonService() { String windowName = "第" + windowId+ "号" + type + "窗口";
Integer number=NumberMachine.getInstance().getCommonManager().fetchServiceNumber();
System.out.println(windowName + "正在获取任务"); if(number !=null){ System.out.println(windowName + "为第" + number + "个" + "普通" + "客户服务"); long beginTime = System.currentTimeMillis(); int maxRand = Constants.MAX_SERVICE_TIME-Constants.MIN_SERVICE_TIME; long serveTime = new Random().nextInt(maxRand)+ 1 + Constants.MIN_SERVICE_TIME; try { Thread.sleep(serveTime); } catch (InterruptedException e) { e.printStackTrace(); } long costTime = System.currentTimeMillis()-beginTime; System.out.println(windowName + "为第" + number + "个" + "普通" + "客户完成服务,耗时" + costTime/1000 + "秒"); }else{ System.out.println(windowName + "没有取到任务,先休息一秒钟"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } private void expressService() { String windowName = "第" + windowId+ "号" + type + "窗口"; Integer number=NumberMachine.getInstance().getExpressManager().fetchServiceNumber(); System.out.println(windowName + "正在获取任务"); if(number !=null){ System.out.println(windowName + "为第" + number + "个" + type + "客户服务"); long beginTime = System.currentTimeMillis(); try { Thread.sleep(Constants.MIN_SERVICE_TIME); } catch (InterruptedException e) { e.printStackTrace(); } long costTime = System.currentTimeMillis()-beginTime; System.out.println(windowName + "为第" + number + "个" + type + "客户完成服务,耗时" + costTime/1000 + "秒"); }else{ System.out.println(windowName + "没有取到任务!"); commonService(); } } |