累病倒了我两次的面试题--移动用户资费统计系统

来源:互联网 发布:高频交易算法 编辑:程序博客网 时间:2024/04/27 18:53

转载:http://blog.csdn.net/zhangxiaoxiang/article/details/6304117


前面的两篇博文写到:有两名同学出去面试,招聘单位分别给他们两个小项目拿回家做,三天内做出来即可给到7k以上的月薪,我都帮他们做了,详情参看《交通灯管理系统》和《银行业务调度系统》的介绍。

  不久,又有一名学员给我打电话,让我帮他做一道类似的题目,不过,这次项目变成了“移动用户资费统计系统”,再细问,知道这次的招聘公司不是软通动力了,而是联想利泰,这两家公司提供的word文档格式都完全一样,我奇怪现在的软件公司怎么都学会用这招来考核求职者了,我真怀疑这些题目出自同一人之手,难道是软通动力的技术经理跳槽到联想利泰啦?他的这招面试手法确实够高!

  我看到“移动用户资费统计系统”的需求文档后,发现这个系统的业务比《交通灯管理系统》和《银行业务调度系统》的业务都要复杂得多,一时间真不知道该从哪里着手, 只能回复那名学员:“这个项目题好像不是一两天就能搞定的事情,我努力做做,别抱太大希望”。如果说“交通灯管理系统”或“银行业务调度系统”做出来就可以拿到7k月薪的工资的话,我认为这个“移动用户资费统计系统”做出来的话,起码应该可以拿到1w以上的月薪。我按照“移动用户资费统计系统”的需求文档认认真真地做了两天,体力透支很大,加之十几年的编程生涯,我一直处于亚健康状态,这个“移动用户资费统计系统”终究成了压倒骆驼的最后一根稻草,我累得病倒了!等到身体康复后,我不甘心事情只做了一半就放弃了,接着又花了两天的时间,总算把这个项目题给做完了,结果又再次累病倒了。
  后来又有好几名去联想利泰面试的学员拿着这个《移动用户资费统计系统》找我,我每次都把源代码给了这些学员,并讲解清楚了其中的代码结构,后来问这些学员,他们一个也没被录取,他们一致认为该公司可能只是想找个人来向他们讲解如何实现此系统的代码,看来着实枉费了我一番心机和功夫!最近,又接到多名学员的反馈,除了联想利泰,美国阿格雅技术有限公司也在使用此题目考核面试者,这个题目虽然没有华丽的外表,但它确实是一个有技术含量的项目,绝非是一个普普通通的程序员容易做出来的东西!这道题目是在解决实实在在的复杂业务问题,其中涵盖了技术含量极高的编程技巧和设计手法,这才是真正做高级项目所要学习的知识,对于广大程序员来说,它是一个不错的案例,不同于那种只是大量重复性工作的增删改查项目。

 
特别说明: 由于电信和银行实际环境的复杂性和产品一旦上线运行后对错误的容忍度几乎为0,电信和银行的项目在做完后都不能直接上线测试运行,而是要通过编写非常完全和严格的模拟程序来进行测试,确保万无一失后再实际上线运行,所以,为电信和银行项目编写模拟程序和比对检查程序运行的结果就非常重要了。虽然我写完了《移动用户资费统计系统》的代码,但不能保证最终的运行结果就没有错误,这需要仔细分析和比对运行结果才能发现问题,由于《移动用户资费统计系统》的业务逻辑实在有点复杂,仅凭我个人之力,实在难以比对出每个细节,为此,我专门编写了《测试用例编写指导书》和《比对检验指导书》,供感兴趣的网友参考。如果有哪位网友发现我写的程序统计出来的结果有问题,请来信详细告知,我将不胜感激。

下面是”移动用户资费统计系统“的需求:

移动用户资费统计系统

原始需求文档下载   讲座ppt下载   讲座源码下载    讲座视频下载(待补充)

-->

模拟实现简易的移动用户资费统计系统逻辑,具体需求如下:

  • 移动运营商A设置两种类型的用户:普通用户及VIP用户,现该运营商已有5个VIP用户和15个普通用户,共计20个用户。
  • 普通用户资费标准如下(不考虑漫游和长途):

【基准资费】

  无月租费用。

通话费:0.6元/ 分钟(仅拨打收费,接听免费)

短信费:0.1元/ 条

数据费:5元/ M

          【优惠套餐】

            话费套餐:月功能费20元,最多可拨打60分钟电话,超出时间按照0.5元/分钟计费。

            短信套餐:月功能费10元,最多可发送200条短信,超出条数按照0.1元/条计费。

            数据套餐:月功能费20元,最多可获50M的流量,超出流量按照3元/M 计费。

注:用户可以选择多种套餐,各功能(通话、短信、数据)计费时,如已选择对应套餐,则按套餐标准计费;如未选择对应套餐,则按对应的基准资费计费。

  • VIP用户资费标准如下(不考虑漫游和长途):

【基准资费】

  月租费用:按天收取,2元/ 天

通话费:0.4元/ 分钟(仅拨打收费,接听免费)

短信费:0.1元/ 条

数据费:3元/ M

          【优惠套餐】

          套餐1 :月基本费用100元(无月租费用),提供如下服务:

                   ①最多可拨打750分钟电话,超出部分按照0.3元/ 分钟计费。

                   ②最多可发送200条短信,超出条数按照0.1元/ 条计费。

                   ③最多可获得100M数据流量,超出流量按照1元/ M计费。

            套餐2 :月基本费用200元(无月租费用),提供如下服务:

                   ①最多可拨打2000分钟电话,超出部分按照0.2元/ 分钟计费。

                   ②最多可发送500条短信,超出条数按照0.1元/ 条计费。

                   ③最多可获得300M数据流量,超出流量按照0.5元/ M计费。

注:用户最多只能选择一种套餐,如未选择任何套餐,则按照基准资费计费。

  • 各类型用户只能选择提供给本类型用户的套餐。
  • 新用户入网。

            ①对于新入网的普通用户,入网当月赠送如下服务:免费拨打60分钟

                电话,免费发送200条短信,免费获得50M流量。超出赠送的部分

                按照普通用户基准资费进行计费。

            ②对于新入网的VIP用户,入网当月赠送如下服务:免费拨打200分

                钟电话,免费发送200条短信,免费获得100M数据流量。超出赠送

                的部分按照VIP用户基准资费进行计费(注意:需按入网天数计算月

                租费用)。

  • 每月为用户计算一次账单,用户订制的套餐信息和账单信息采用文件方式进行存储(提示:可使用java中的Properties API进行文件操作)。
  • 用户可自由订制或退订所属用户类型的套餐,并从下月起生效。
  • 异步随机生成客户操作如下:

①拨打电话,每次拨打时长为1至10分钟不等(随机决定,以分钟为单位)。

②发送短信,每次发送条数为1至10条不等(随机决定)。

③上网获取数据,每次获取数据流量可为50K,100K,200K,500K,1M(随机决定)。

④订制或退订相应套餐。

⑤新用户入网(随机决定用户类型)。

注:随机生成客户操作时间间隔自定,可设置。

  • 不要求实现GUI,只考虑系统逻辑实现,可通过Log方式展现程序运行结果。 

 

解题思路

 

  • 数据分析与统一计算公式:

分析本系统的业务,可以看到普通用户和VIP用户在订购套餐的方式以及月底计算账单的公式上都有很大的不同:
(1)普通用户没有月租费和月基本费、而VIP用户有月租费或月基本费。
(2)普通用户是单独订购电话、短信和数据套餐,每项套餐单独收取月功能费;VIP用户不能单独订购电话、短信和数据套餐,VIP用户订购的套餐中同时包含了电话、短信和数据等服务功能。

我们可以为普通用户和VIP用户分别设计出一个月底计算账单的公式,但是,为了简化编程,我们也可以为两种不同用户设计出一个统一的月底计算账单的公式,这就好比“大象有尾巴,而蚂蚁没有尾巴,大象没有触角,而蚂蚁则有触角,能否用同一个累加所有器官的公式来计算蚂蚁和大象的体重呢?当然可以,这时候只需要假设蚂蚁也有尾巴,只是蚂蚁的尾巴重量为0,假设大象也有触角,只是大象触角的重量为0,这样,就可以用同一种累加所有器官的公式来计算蚂蚁和大象的体重了。”我们可以采用如下方式来统一各类用户在各种情况下的费用计算公式:

     (1) 月基本费或月租费:月基本费方式为固定值,月租费方式为当月总天数*每天费用或者(当月总天数-入网日+1)*每天费用,只有vip用户才存在此项费用,但是为了统一计算公式,可以认为普通用户也有此项费用,值为0。

     (2) 电话收费时长:等于(电话时长-免费时长),计算后的值小于0则记为0,免费时长又分为两类:新入网的免费和套餐中的免费,新入网的免费在用户对象中处理,套餐中的免费封装在套餐策略对象中处理。

     (3) 电话、短信、数据套餐月功能费:只有普通用户定了套餐才有此项费用,但是为了统一计算公式,可以认为没定此功能套餐的普通用户和vip用户也有此项费用,值为0。
     (4) 月电话费用=电话套餐月功能费+单位计费价格*电话收费时长
     (5) 按月电话费用的相同规则计算月短信费用和月数据费用
     (6) 月总计费用=月基本费或月租费 + 月电话费用 + 月短信费用 + 月数据费用

我们可以用如下一幅“月账单费用的组成成分”图来直观地理解上面的计算公式:

 

  • 采用一种便于程序代码读取的格式在配置文件中存储各项数据

刚开始猛然看到这么多数据项,肯定会感觉纷繁杂乱,理不出头绪来,但是,不管这些数据项有多么多,归结起来,不就是某个用户要使用自己的某种数据吗?只是不同的用户有不同的数据罢了,每个用户只需要关心和使用自己的数据、而不用关心其他用户的数据就显得简单多了,因此可以写一个类来专门读取用户的数据,在配置文件中存储的各项数据应想办法采用一种便于该类读取的格式。

(1) 要存储的数据项有:功能单价费用、功能套餐免费数量、功能套餐月费用、新入网免费数量、整体月基本费或月租费。
(2) 一些数据还要随以下类型进行区分:用户类型、套餐类型、功能类型。
(3) 在配置文件中通过用点(.)对数据项名称进行分级的方式来区分各个数据项所属的类别和功能,如下所示:
         common.normal.phone.price --> 表示普通用户/非套餐/电话/单价
         common.pack1.phone.price --> 表示普通用户/套餐/电话/单价
         common.pack1.phone.free --> 表示普通用户/套餐/电话/免费数量
         common.pack1.phone.rent ?表示普通用户/套餐/电话/套餐月功能费用

 

         vip.normal.phone.price --> 表示VIP用户/非套餐/电话/单价
         vip.pack1.phone.price --> 表示VIP用户/套餐1/电话/单价
         vip.pack2.phone.price --> 表示VIP用户/套餐2/电话/单价

 

         common.new.phone.free --> 表示普通用户/新开户/电话/免费数量
         vip.new.phone.free --> 表示VIP用户/新开户/电话/免费数量
(4) 对于值为0的数据项,不用在配置文件中存储,这样,当程序代码从配置文件中没有读取到该数据项时,即认为该值为0。
(5) 对于vip用户的整体月基本费或月租费,由于计费单位不一样,采用配置文件方式存储将增加程序的复杂度,所以,决定直接在程序代码中硬编码。

为了便于程序编写,在配置文件中要注意如下两点:
    (1) 由于程序中要求每次传输的数据量都是10k的整数倍,因此可以将数据通信费的单价单位由M转换成K表示,由于数据通信费的价格5元/M,转换后则是0.5分/K,这样程序中就涉及到小数处理了。由于在程序中处理小数是很繁琐和容易出现误差的事情,所以,最好还是想办法先统一转换成整数形式进行处理,由于数据传输量都是10k的整数倍,因此,想到将数据通信费的价格5元/M转换成5分/10K。因此,在配置文件中将所有的价格和费用的计量单位由元转换成分表示。
    (2) 后来在配置文件中填写各项数据时,发现VIP用户订购套餐2时的数据费仅为0.5元/M,这时候转换的结果是0.5分/10k,又还是出现了小数,故想到把计费单位转成5厘/10k,所以,在配置文件中最终还是应将所有的价格和费用的计量单位由元转换成厘进行计费。
按照上面这些思想设计和编写出来的配置文件conf.properties的完整内容如下:

[c-sharp] view plaincopy
  1. common.normal.phone.price=600  
  2. common.normal.message.price=100  
  3. common.normal.data.price=50  
  4.   
  5. common.pack1.phone.price=500  
  6. common.pack1.message.price=100  
  7. common.pack1.data.price=30  
  8. common.pack1.phone.rent=20000  
  9. common.pack1.message.rent=10000  
  10. common.pack1.data.rent=20000  
  11. common.pack1.phone.free=60  
  12. common.pack1.message.free=200  
  13. common.pack1.data.free=5000  
  14.   
  15. vip.normal.phone.price=400  
  16. vip.normal.message.price=100  
  17. vip.normal.data.price=30  
  18.   
  19. vip.pack1.phone.price=300  
  20. vip.pack1.message.price=100  
  21. vip.pack1.data.price=10  
  22. vip.pack1.phone.free=750  
  23. vip.pack1.message.free=200  
  24. vip.pack1.data.free=10000  
  25.   
  26. vip.pack2.phone.price=200  
  27. vip.pack2.message.price=100  
  28. vip.pack2.data.price=5  
  29. vip.pack2.phone.free=2000  
  30. vip.pack2.message.free=500  
  31. vip.pack2.data.free=30000  
  32.   
  33. common.new.phone.free=60  
  34. common.new.message.free=200  
  35. common.new.data.free=5000  
  36.   
  37. vip.new.phone.free=200  
  38. vip.new.message.free=200  
  39. vip.new.data.free=10000  
 
 

接着可编写一个读取上面的配置文件中的各项数据的ConfigManager类,该类根据用户类型、套餐类型、业务功能类别来读取相应功能套餐的单价、免费数量、功能费,以及新用户免费数量。源码如下:

[c-sharp] view plaincopy
  1. public class ConfigManager {  
  2.     private static Properties config = new Properties();  
  3.     static{  
  4.         InputStream ips = ConfigManager.class.getResourceAsStream("/conf.properties");  
  5.         try {  
  6.             config.load(ips);  
  7.         } catch (IOException e) {  
  8.             throw new ExceptionInInitializerError(e);  
  9.         }  
  10.     }  
  11.       
  12.     private static String makePrefix(int customerType,int packType,int businessType){  
  13.         String customerTitle = customerType==0?"common":"vip";  
  14.         String packTitle = packType==0?"normal":("pack"+packType);  
  15.         String businessTitle = businessType==0?"phone":businessType==1?"message":"data";  
  16.         return customerTitle + "." + packTitle + "." + businessTitle;  
  17.     }  
  18.       
  19.     private static int getNumber(String key){  
  20.         String value = config.getProperty(key);  
  21.         try{  
  22.             return Integer.parseInt(value);  
  23.         }catch(Exception e){  
  24.             return 0;  
  25.         }         
  26.     }  
  27.       
  28.     public static int getPrice(int customerType,int packType,int businessType){  
  29.         return getNumber(makePrefix(customerType,packType,businessType)+".price");  
  30.     }  
  31.       
  32.     public static int getFree(int customerType,int packType,int businessType){  
  33.         return getNumber(makePrefix(customerType,packType,businessType)+".free");  
  34.     }  
  35.       
  36.     public static int getRent(int customerType,int packType,int businessType){  
  37.         return getNumber(makePrefix(customerType,packType,businessType)+".rent");  
  38.     }  
  39.       
  40.     public static int getNewCustomerFree(int customerType,int businessType){  
  41.         String[] businesses = {"phone","message","data"};  
  42.         return getNumber((customerType==0?"common":"vip")+".new." + businesses[businessType] + ".free");  
  43.     }  
  44. }  
  • 面向对象的分析和设计:

在进行面向对象设计之前,必须具备和把握了一个重要的经验:谁拥有数据,谁就对外提供操作这些数据的方法。大家可能会说,刚开始看到需求时,只知道某一个用户要使用很多各种各样的数据,而想不到要延伸出哪些对象,其实,只要你把所有数据和使用这些数据的方法归纳起来形成对象,自然就可以发掘出这些对象了。

 

(一)移动公司里面有两类客户,移动公司里的客户可以打电话、发短信、数据通信,还可以订购和退订套餐;移动公司每月要为其中所有客户生成计费清单,还要模拟各种客户的行为。据此,可以分析出如下一些类和方法:


(1) MobileCorporation类:simulationBusiness方法(模拟一个月的业务,内部随机做500件事情和结算每个用户的计费情况,随机做的事情就是挑选一个用户做其中任何一件事情:打电话/发短信/数据通信/定套餐/退订套餐/新用户入网)
(2) Customer、CommonCustomer、VipCustomer等类:普通用户和VIP用户都可以打电话/发短信/数据通信/定套餐/退订套餐/结算费用等方法。普通用户和VIP用户的区别在于定套餐、退订套餐、结算费用的策略对象不同。

 

(二)凭借积累的面向对象设计的经验,可以把计算电话、短信、数据费用的功能各封装成一个策略对象,这些策略对象内部根据当前的用户类别、当月适用的套餐和计费的功能项目来计算费用。策略对象在计算费用时,要从Properties文件中读取相应的数据值,为此可以专门设计一个类来读取配置文件,策略对象调用该类的方法。据此,可以分析出如下一些类和方法:


(1) ComputeStrategy类:包含computeMoney方法
(2) ConfigManager类: 包含getPrice、getFree、getRent、getNewCustomerFree等方法。

 

(三)另外,应该有一个总的策略存储对象来管理当前用户的各个功能项目的策略对象以及VIP用户的月租费或月基本费,所谓订购某项功能套餐,就是选用哪个策略对象,所以,订购某个功能套餐和退订某个功能套餐的方法应分配给这个总的策略存储对象。这个总的策略存储对象内部既要存储各个功能项的当前的套餐对应的策略对象、又要存储下月订购的套餐,还要在下个月时将订购的套餐“设置”为当前的套餐,这个“设置”不一定是真的变量赋值操作,可以是通过日期比较的方式来达到,这需要设计一个辅助类把某月和从该月开始订购的功能套餐进行关联存储。据此,可以分析出如下一些类和方法:


(1) PackStrategy类:包含orderRent、cancelRent、getValidRent、orderPack、cancelPack、getValidPack等方法
(2)OrderedStrategyHolder类:包含order、getValidStrategy等方法
(3)Rent类:包含computeRent方法 

 

(四)类图:

 

             

(五)计算账单费用的各个对象的作用与关系

  • 类的编码实现

(一)MobileCorporation类(代表移动公司)
1.在MobileCorporation类内部定义一个List集合的成员变量,用于存储移动公司的所有用户,这里不需要区分普通用户和VIP用户,而是把他们抽象成用户这个父类,这样就可以采用统一的方式来调用他们各自的行为,普通用户和VIP用户的行为差异,在它们各自的方法内部体现,这正是充分利用了面向对象的抽象和多态特性。
2.在构造方法中,向用于存储所有用户的List集合中增加15名普通用户和5名VIP用户,每名用户需要有自己的用户名和入网日期。
3.在MobileCorporation类中定义一个simulationBusiness(Date month)方法来模拟某个月的业务活动,首先清除用户上月的记录信息,然后再模拟发生如下一些事情:某个用户打电话、某个用户发短信、某个用户传输数据、某个用户订购套餐、某个用户退订套餐、新用户入网,最后再统计出各个用户在本月的账单信息。模拟发生的事情随机发生,总共模拟发生500次,并让打电话、发短信、传输数据等事情发生的概率为订购套餐、退订套餐、新用户入网的20倍。
4.将模拟随机发生一件事情的过程封装成一个私有方法randDoOneThing(Date month),这个方法内部调用的某个用户打电话、某个用户发短信、某个用户传输数据、某个用户订购套餐、某个用户退订套餐、新用户入网等功能又各自封装成一个私有方法。
源码如下:

 

[c-sharp] view plaincopy
  1. package cn.itcast.mobilecounter.strategy;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Calendar;  
  5. import java.util.Date;  
  6. import java.util.Random;  
  7.   
  8. public class MobileCorporation {  
  9.     private ArrayList<Customer> customers = new ArrayList<Customer>();  
  10.       
  11.     public MobileCorporation(){  
  12.         for(int i=1;i<=15;i++){  
  13.             customers.add(  
  14.                     new CommonCustomer(i+"号普通客户",new Date(108,10,1))  
  15.             );  
  16.         }  
  17.           
  18.         for(int i=1;i<=5;i++){  
  19.             customers.add(            
  20.                     new VIPCustomer(i+"号VIP客户",new Date(108,10,1))  
  21.             );  
  22.         }  
  23.         System.out.println("程序创建了运营商已有的5个VIP用户和15个普通用户,并设置他们的入网日期为2008年10月1日.");  
  24.     }  
  25.       
  26.     //模拟某个月的业务活动  
  27.     public void simulationBusiness(Date month){  
  28.         for(Customer customer : customers){  
  29.             customer.monthBegin();  
  30.         }  
  31.           
  32.         System.out.println("--------being simulating " + DateUtil.formatDateToMonth(month) + "--------------");   
  33.         for(int i=0;i<500/*30*/;i++){  
  34.             randDoOneThing(month);  
  35.         }  
  36.           
  37.         System.out.println(DateUtil.formatDateToMonth(month)+"的计费汇总清单:");  
  38.         //汇总所有人的账单  
  39.         for(int i=0;i<customers.size();i++){  
  40.             customers.get(i).countMonthMoney(month);  
  41.         }  
  42.   
  43.     }  
  44.     /** 
  45.      * 随机调用下面的某一个方法 
  46.      * */  
  47.     private void randDoOneThing(Date month){  
  48.         Calendar calendar = Calendar.getInstance();  
  49.         calendar.setTime(month);  
  50.         calendar.add(Calendar.MONTH, 1);  
  51.         Date monthOfOrderPack = calendar.getTime();           
  52.         /*让orderPack、cancelPack、joinNewCustomer的出现概率是其他操作的1/20。*/             
  53.         int rand = new Random().nextInt(63);  
  54.         if(rand>=0 && rand<20){  
  55.             callPhone();  
  56.         }  
  57.         else if(rand>=20 && rand<40){           
  58.             sendMessage();  
  59.         }  
  60.         else if(rand>=40 && rand<60){           
  61.             transferData();  
  62.         }else{  
  63.             switch(rand){  
  64.                 case 60:          
  65.                     orderPack(monthOfOrderPack);  
  66.                     break;  
  67.                 case 61:                      
  68.                     cancelPack(monthOfOrderPack);  
  69.                     break;  
  70.                 case 62:  
  71.                     joinNewCustomer(month);  
  72.                     break;    
  73.             }  
  74.         }  
  75.     }  
  76.     /** 
  77.      * 随机选中一个用户,让其随机拨打的电话时长为1至10分钟不等 
  78.      */  
  79.     private void callPhone(){  
  80.         int rand = new Random().nextInt(customers.size());  
  81.         Customer customer = customers.get(rand);  
  82.         int phoneTimes = new Random().nextInt(10) + 1;  
  83.         customer.callPhone(phoneTimes);  
  84.         System.out.println(customer + "打了" + phoneTimes + "分钟电话");  
  85.     }  
  86.       
  87.     /** 
  88.      * 随机选中一个用户,让其随机发送的短信数目为1至10条不等 
  89.      */       
  90.     private void sendMessage(){  
  91.         int rand = new Random().nextInt(customers.size());  
  92.         Customer customer = customers.get(rand);  
  93.         int messageNumbers = new Random().nextInt(10) + 1;  
  94.         customer.sendMessage(messageNumbers);  
  95.         System.out.println(customer + "发了" + messageNumbers + "条短信");  
  96.     }  
  97.     /** 
  98.      * 随机选中一个用户,让其随机获取的数据流量为50K,100K,200K,500K,1M 
  99.      */   
  100.     private void transferData(){  
  101.         int rand = new Random().nextInt(customers.size());  
  102.         Customer customer = customers.get(rand);  
  103.           
  104.         int [] dataSize = new int[]{50,100,200,500,1000};  
  105.         int randSizeKey = new Random().nextInt(5);  
  106.         customer.transferData(dataSize[randSizeKey]);  
  107.         System.out.println(customer + "传送了" + dataSize[randSizeKey] + "k数据");         
  108.     }  
  109.     /** 
  110.      * 随机选中一个用户,为其随机订购一款套餐 
  111.      */   
  112.     private void orderPack(Date month){  
  113.         int rand = new Random().nextInt(customers.size());  
  114.         customers.get(rand).randomOrderPack(month);  
  115.     }  
  116.     /** 
  117.      * 随机选中一个用户,并将其已经有的套餐取消 
  118.      */  
  119.     private void cancelPack(Date month){  
  120.         int rand = new Random().nextInt(customers.size());  
  121.         customers.get(rand).randomCancelPack(month);  
  122.     }  
  123.       
  124.     private void joinNewCustomer(Date month){  
  125.         Calendar calendar = Calendar.getInstance();  
  126.         calendar.setTime(month);  
  127.         int maxDay = calendar.getMaximum(Calendar.DAY_OF_MONTH);  
  128.         int randDay = new Random().nextInt(maxDay) + 1;  
  129.         /*下面的复制过程很重要,不能直接修改date,当然最好是对Calendar直接操作 
  130.          * 这里是为了演示要注意clone而保留的。 
  131.          */   
  132.         Date joinTime = (Date)month.clone();  
  133.         joinTime.setDate(randDay);  
  134.           
  135.         int randType = (new Random().nextInt(10))%2;  
  136.         Customer customer = null;  
  137.         if(randType == 0){  
  138.             int commonId = IdGenerator.getInstance().nextCommonId();  
  139.             customer = new CommonCustomer(commonId+"号普通客户",joinTime);  
  140.             customers.add(customer);  
  141.         }else{  
  142.             int vipId = IdGenerator.getInstance().nextVipId();    
  143.             customer = new VIPCustomer(vipId+"号VIP客户",joinTime);  
  144.             customers.add(customer);  
  145.         }  
  146.         System.out.println(DateUtil.formatDateToDay(joinTime) + "新注册了" + customer);  
  147.     }  
  148.       
  149. }  

(二)IdGenerator类(新用户生成新Id编号)
1.由于系统中原来已经有了15名普通用户和5名VIP用户,所以,新产生的普通用户的编号应从16开始,新产生的VIP用户的编号应该从6开始。
2.把该类写成单例,逻辑上更为严谨,在前面的博文中有人批评我写程序不必那么严谨、凑合即可,那就请思考为什么我们一直做不出奔驰这样精致的汽车的原因,因为凑合的想法在很多国人心中已经根深蒂固了,马马虎虎已经是我等中国人的优良传统了,但我并不想继承这一优良传统。
源码如下:

[c-sharp] view plaincopy
  1. public class IdGenerator {  
  2.     private IdGenerator(){  
  3.           
  4.     }  
  5.     private static IdGenerator instance = new IdGenerator();  
  6.     public static IdGenerator getInstance(){  
  7.         return instance;  
  8.     }  
  9.       
  10.     private int lastCommonId = 15;  
  11.     private int lastVipId = 5;  
  12.       
  13.     public synchronized int nextCommonId(){  
  14.         return ++lastCommonId;  
  15.     }  
  16.       
  17.     public synchronized int nextVipId(){  
  18.         return ++lastVipId;  
  19.     }  
  20. }  

(三)MainClass类(整个程序的主运行类)
1.调用MobileCorporation类的simulationBusiness(Date date)方法,总共模拟15个连续的月份。
源码如下:

[c-sharp] view plaincopy
  1. public class MainClass {  
  2.   
  3.     public static void main(String[] args) {  
  4.         MobileCorporation corp = new MobileCorporation();  
  5.         //设置要模拟的起始月份  
  6.         Date month = new Date(109,0,1);   
  7.         System.out.println("程序开始模拟从2009年1月1日开始,连续15个月的运行情况.");        
  8.         //总共模拟15个连续的月份  
  9.         for(int i=0;i<15/*3*/;i++){  
  10.             corp.simulationBusiness(month);  
  11.   
  12.             Calendar calendar = Calendar.getInstance();  
  13.             calendar.setTime(month);  
  14.             calendar.add(Calendar.MONTH, 1);  
  15.             month = calendar.getTime();  
  16.         }  
  17.     }  
  18. }  

(四)Customer类(普通用户与VIP用户的抽象父类)
1.在Customer类中定义了用户名称和入网时间;还定义了4个List集合的成员变量,分别用于存储用户每次拨打的电话时间、每次发送的短信数量和每次传输的数据量,以及用户的操作列表;此外, Customer类中还定义了一个用于计算当月账单费用的策略存储对象,它用于存储用户选择的各项功能套餐的策略对象。
2.在Customer类中定义打电话、发短信、传输数据的方法,这些方法分别为对应的List集合增加记录,并且都需要向操作列表集合中增加记录。此外,由于普通用户和VIP用户定套餐和退订套餐的方式有很大的区别,所以,这两个功能在Customer类中对应的方法被定义成了抽象的,这两个方法由普通用户和VIP用户根据自己的实际情况去具体实现。
3.在Customer类中定义了一个countMonthMoney方法来计算用户当前月的账单费用,首先从电话、短信、数据等集合中累加出各项功能的数量,对于新用户,则减去新用户要优惠的数量,然后再将这些数量分别传递给用户订购的相应的策略对象去计算费用,最后汇总和打印出总费用。
源码如下:

[c-sharp] view plaincopy
  1. public abstract class Customer {  
  2.     protected String name;  
  3.     //用户入网的时间  
  4.     private Date joinTime;  
  5.     private int customerType = 0;  
  6.     protected List<ActionRecord> actionRecords = new ArrayList<ActionRecord>();  
  7.       
  8.     //积累的结果只表示当月的所有通话记录,不代表所有历史记录  
  9.     private ArrayList phoneRecords = new ArrayList();  
  10.     //积累的结果只表示当月的所有短信记录,不代表所有历史记录  
  11.     private ArrayList messageRecords = new ArrayList();  
  12.     //积累的结果只表示当月的所有数据传送记录,不代表所有历史记录  
  13.     private ArrayList dataRecords = new ArrayList();  
  14.     protected PackStrategy packStrategy;  
  15.   
  16.     public void monthBegin(){  
  17.         phoneRecords.clear();  
  18.         messageRecords.clear();  
  19.         dataRecords.clear();  
  20.         actionRecords.clear();  
  21.     }  
  22.       
  23.     public Customer(String name,Date joinTime,int customerType){  
  24.         this.name = name;  
  25.         this.joinTime = joinTime;  
  26.         this.customerType = customerType;  
  27.     }  
  28.   
  29.     public String toString(){  
  30.         return name;  
  31.     }  
  32.       
  33.     public void callPhone(int times){  
  34.         phoneRecords.add(times);  
  35.         actionRecords.add(new ActionRecord("打电话",times + "分钟"));  
  36.     }  
  37.     public void sendMessage(int numbers){  
  38.         messageRecords.add(numbers);  
  39.         actionRecords.add(new ActionRecord("发短信",numbers + "条"));         
  40.     }  
  41.     public  void transferData(int size){  
  42.         dataRecords.add(size);  
  43.         actionRecords.add(new ActionRecord("传数据",size + "k"));            
  44.     }  
  45.   
  46.     /** 
  47.      *  
  48.      * @param currentMonth 正在被计费处理的当月的日期, 
  49.      * 注意:日字段设置为1,以便于方法内部计算是否是新用户 
  50.      */   
  51.     public int countMonthMoney(Date currentMonth){  
  52.         boolean newcome = !joinTime.before(currentMonth);//joinTime.after(currentMonth);  
  53.           
  54.         int totalPhone = gatherRecords(phoneRecords);  
  55.         int totalMessage = gatherRecords(messageRecords);  
  56.         int totalData = gatherRecords(dataRecords);  
  57.           
  58.         int freePhone = 0;  
  59.         int freeMessage = 0;  
  60.         int freeData = 0;  
  61.         if(newcome){  
  62.             freePhone = ConfigManager.getNewCustomerFree(customerType,0);  
  63.             freeMessage = ConfigManager.getNewCustomerFree(customerType,1);  
  64.             freeData = ConfigManager.getNewCustomerFree(customerType,2);      
  65.         }  
  66.           
  67.         int chargePhone = totalPhone>freePhone?totalPhone-freePhone:0;  
  68.         int chargeMessage = totalMessage>freeMessage?totalMessage-freeMessage:0;  
  69.         int chargeData = totalData>freeData?totalData-freeData:0;                  
  70.           
  71.         //汇总打印:包括姓名,入网日期,统计月份,通话清单,费用清单,总费用。  
  72.         System.out.println(name + "," + DateUtil.formatDateToDay(joinTime) + "入网.");  
  73.         System.out.println(" 操作清单如下-----");   
  74.             for(int i=0;i<actionRecords.size();i++){  
  75.                 System.out.println("  " + actionRecords.get(i));  
  76.             }  
  77.         System.out.println(" 统计清单如下-----");  
  78.         System.out.println("  通话:" + phoneRecords + "分钟:短信" + messageRecords + "条:数据" + dataRecords + "k");  
  79.         System.out.println("  通话累计:" + totalPhone + "分钟,减除新开户" + freePhone + "分钟,实际收费" + chargePhone + "分钟");  
  80.         System.out.println("  短信累计:" + totalMessage + "条,减除新开户" + freeMessage + "条,实际收费" + chargeMessage + "条");  
  81.         System.out.println("  数据累计:" + totalData + "k,减除新开户" + freeData + "k,实际收费" + chargeData + "k");  
  82.   
  83.           
  84.           
  85.         ComputeStrategy phoneStrategy = packStrategy.getValidPhonePack(currentMonth);  
  86.         ComputeStrategy messageStrategy = packStrategy.getValidMessagePack(currentMonth);  
  87.         ComputeStrategy dataStrategy = packStrategy.getValidDataPack(currentMonth);  
  88.           
  89.         int sum = 0;  
  90.         //VIP用户才有月租金或基本费  
  91.         Rent rent = packStrategy.getValidRent(currentMonth);  
  92.         if(rent != null){  
  93.             int rentMoney = rent.coputeRent(joinTime,currentMonth);  
  94.             sum +=  rentMoney;  
  95.             System.out.println("  月租费或基本费:" + rentMoney + "厘钱");              
  96.         }  
  97.           
  98.         sum += phoneStrategy.computeMoney(chargePhone);  
  99.         sum += messageStrategy.computeMoney(chargeMessage);  
  100.         sum += dataStrategy.computeMoney(chargeData/10);  
  101.         System.out.println("  总计:" + sum/1000f + "元钱");  
  102.         return sum;  
  103.     }  
  104.       
  105.     private int gatherRecords(ArrayList records){  
  106.         int sum = 0;  
  107.         for(int i=0;i<records.size();i++){  
  108.             sum +=  (Integer)(records.get(i));  
  109.         }  
  110.         return sum;  
  111.     }  
  112.       
  113.     public abstract void randomCancelPack(Date month);    
  114.     public abstract void randomOrderPack(Date month);     
  115.   
  116. }  

(五)ActionRecord类(代表用户的一项操作)
1.代表用户的一项操作信息,包含操作名称和数量。
源码如下:

[c-sharp] view plaincopy
  1. public class ActionRecord {  
  2.     private String name;  
  3.     private String value;  
  4.     public ActionRecord(String name, String value) {  
  5.         this.name = name;  
  6.         this.value = value;  
  7.     }  
  8.       
  9.     public String toString(){  
  10.         return name + ":" + value;  
  11.     }  
  12. }  

(六)CommonCustomer类(代表普通用户)
1.在构造方法中为策略存储对象赋初始值,即用户类型为0、各项功能的套餐类别为0,月租金或月基本费对象为null。
2.实现订购套餐和退订套餐的功能,通过产生随机数来决定是订购和退订哪一项功能的套餐,订购某个功能套餐就是将相应的策略对象的类型设置为1,退订某个功能套餐就是将相应的策略对象的类型设置为0。其中的代码省略了一些琐碎的细节,包括阻止用户再次订购已经订购了的功能套餐、阻止用户退订根本没有订购过的套餐。

源码如下:

[c-sharp] view plaincopy
  1. public class CommonCustomer extends Customer {  
  2.   
  3.     public CommonCustomer(String name,Date joinTime){  
  4.         super(name,joinTime,0);  
  5.         packStrategy = new PackStrategy(0,0,null);  
  6.         actionRecords.add(new ActionRecord(name, DateUtil.formatDateToDay(joinTime)+"入网"));       
  7.     }  
  8.       
  9.     public void randomCancelPack(Date orderedMonth){  
  10.         int rand = new Random().nextInt(3);  
  11.         switch(rand){  
  12.         case 0:  
  13.             /*if(packStrategy.getOrderedPhonePack() == null || packStrategy.getOrderedPhonePack().getPackType() == 0){ 
  14.                 System.out.println(name + "试图退订根本就没有订过的电话套餐");           
  15.                 return; 
  16.             }*/           
  17.             packStrategy.cancelPhonePack(orderedMonth);  
  18.             System.out.println(name + "退订了" + "电话套餐" + "(从" + DateUtil.formatDateToMonth(orderedMonth) + "开始)");      
  19.             actionRecords.add(new ActionRecord("退订电话套餐",""));     
  20.             break;  
  21.         case 1:  
  22.             /*if(packStrategy.getOrderedMessagePack() ==null || packStrategy.getOrderedMessagePack().getPackType() == 0){ 
  23.                 System.out.println(name + "试图退订根本就没有订过的短信套餐");           
  24.                 return; 
  25.             }*/           
  26.             packStrategy.cancelMessagePack(orderedMonth);     
  27.             System.out.println(name + "退订了" + "短信套餐" + "(从" + DateUtil.formatDateToMonth(orderedMonth) + "开始)");      
  28.             actionRecords.add(new ActionRecord("退订短信套餐",""));  
  29.             break;  
  30.         case 2:  
  31. /*          if(packStrategy.getOrderedDataPack()==null || packStrategy.getOrderedDataPack().getPackType() == 0){ 
  32.                 System.out.println(name + "试图退订根本就没有订过的数据套餐");           
  33.                 return; 
  34.             }   */        
  35.             packStrategy.cancelDataPack(orderedMonth);    
  36.             System.out.println(name + "退订了" + "数据套餐" + "(从" + DateUtil.formatDateToMonth(orderedMonth) + "开始)");      
  37.             actionRecords.add(new ActionRecord("退订数据套餐",""));  
  38.             break;  
  39.         }  
  40.     }  
  41.       
  42.     public void randomOrderPack(Date month){  
  43.         int rand = new Random().nextInt(3);  
  44.         switch(rand){  
  45.         case 0:  
  46.             //if(packStrategy.getOrderedPhonePack()==null || packStrategy.getOrderedPhonePack().getPackType() == 0){  
  47.                 packStrategy.orderPhonePack(month,1);  
  48.                 System.out.println(name + "订购了" + "电话套餐" + "(从" + DateUtil.formatDateToMonth(month) + "开始)");         
  49.                 actionRecords.add(new ActionRecord("定电话套餐",""));      
  50.             //}  
  51.             break;  
  52.         case 1:  
  53.             //if(packStrategy.getOrderedMessagePack() == null || packStrategy.getOrderedMessagePack().getPackType() == 0){            
  54.                 packStrategy.orderMessagePack(month,1);   
  55.                 System.out.println(name + "订购了" + "短信套餐" + "(从" + DateUtil.formatDateToMonth(month) + "开始)");         
  56.                 actionRecords.add(new ActionRecord("定短信套餐",""));          
  57.             //}  
  58.             break;  
  59.         case 2:  
  60.             //if(packStrategy.getOrderedDataPack() == null || packStrategy.getOrderedDataPack().getPackType() == 0){              
  61.                 packStrategy.orderDataPack(month,1);      
  62.                 System.out.println(name + "订购了" + "数据套餐" + "(从" + DateUtil.formatDateToMonth(month) + "开始)");     
  63.                 actionRecords.add(new ActionRecord("定数据套餐",""));      
  64.             //}  
  65.             break;  
  66.         }  
  67.     }         
  68. }  

(七)VIPCustomer类(代表普通用户)
1.在构造方法中为策略存储对象赋初始值,即用户类型为1、各项功能的套餐类别为0,月租金或月基本费对象为按天计算月租金。
2.实现订购套餐和退订套餐的功能,通过产生随机数来决定是订购和退订套餐1或套餐2。订购套餐1或套餐2就是将各个功能套餐相应的策略对象的类型都设置为1或2,并设置相应的Rent对象;退订套餐就是将各个功能套餐相应的策略对象的类型都设置为0,并设置相应的Rent对象为按天计算月租金。其中的代码省略了一些琐碎的细节,包括阻止用户再次订购已经订购了的功能套餐、用户退订根本没有订购过的套餐。
源码如下:

[c-sharp] view plaincopy
  1. public class VIPCustomer extends Customer {  
  2.   
  3.     public VIPCustomer(String name,Date joinTime){  
  4.         super(name,joinTime,1);  
  5.         packStrategy = new PackStrategy(1,0,new Rent(200,RentUnit.DAY));  
  6.         actionRecords.add(new ActionRecord(name, DateUtil.formatDateToDay(joinTime)+"入网"));  
  7.     }  
  8.   
  9.     public void orderPack1(Date month){  
  10. /*      if(packStrategy.getOrderedPhonePack()==null || packStrategy.getOrderedPhonePack().getPackType() != 1) 
  11.         {       */  
  12.             packStrategy.orderRent(month,new Rent(10000,RentUnit.MONTH));  
  13.             packStrategy.orderPhonePack(month,1);  
  14.             packStrategy.orderMessagePack(month,1);  
  15.             packStrategy.orderDataPack(month,1);  
  16.             System.out.println(name+ "订购了套餐1" + "(从" + DateUtil.formatDateToMonth(month) + "开始)" );                   
  17.             actionRecords.add(new ActionRecord("订购套餐1",""));      
  18.         //}  
  19.     }  
  20.       
  21.     public void orderPack2(Date month){  
  22. /*      if(packStrategy.getOrderedPhonePack() ==null || packStrategy.getOrderedPhonePack().getPackType() != 2) 
  23.         {*/  
  24.             packStrategy.orderRent(month,new Rent(20000,RentUnit.MONTH));  
  25.             packStrategy.orderPhonePack(month,2);  
  26.             packStrategy.orderMessagePack(month,2);  
  27.             packStrategy.orderDataPack(month,2);  
  28.             System.out.println(name+ "订购了套餐2" + "(从" + DateUtil.formatDateToMonth(month) + "开始)" );                   
  29.             actionRecords.add(new ActionRecord("订购套餐2",""));      
  30.         //}  
  31.     }  
  32.       
  33.     public void randomCancelPack(Date orderedMonth){  
  34.         /* 
  35.         if(packStrategy.getOrderedPhonePack() ==null || 
  36.             packStrategy.getOrderedPhonePack().getPackType() == 0){ 
  37.         System.out.println(name + "试图退订根本就没有订过的套餐"); return; } 
  38.          */  
  39.         packStrategy.orderRent(orderedMonth, new Rent(200, RentUnit.DAY));  
  40.         packStrategy.orderPhonePack(orderedMonth, 0);  
  41.         packStrategy.orderMessagePack(orderedMonth, 0);  
  42.         packStrategy.orderDataPack(orderedMonth, 0);  
  43.         System.out.println(name + "退订了" + "套餐" + "(从"  
  44.                 + DateUtil.formatDateToMonth(orderedMonth) + "开始)");  
  45.         actionRecords.add(new ActionRecord("退定套餐"""));                      
  46.     }  
  47.       
  48.     public void randomOrderPack(Date month){  
  49.         //如果以前订购过某套餐,现在仍然可以重新订购该套餐  
  50.         int randType = (new Random().nextInt(10))%2;  
  51.         if(randType == 0){  
  52.             orderPack1(month);        
  53.         }else if(randType == 1){  
  54.             orderPack2(month);        
  55.         }  
  56.     }     
  57. }  

(八)DateUtil类(将日期格式化成字符串的辅助类)
源码如下:

 

[c-sharp] view plaincopy
  1. public class DateUtil {  
  2.     public static String formatDateToMonth(Date date){  
  3.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");  
  4.         String result = sdf.format(date);  
  5.         return result;  
  6.     }  
  7.       
  8.     public static String formatDateToDay(Date date){  
  9.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");  
  10.         String result = sdf.format(date);  
  11.         return result;  
  12.     }     
  13. }  

 

(九)ComputeStrategy类(计算某项功能费用的策略类)
1.该类用于根据用户类型、套餐类型、业务功能类别来计算当月的某项业务功能的费用,其内部采用同一种算法公式来处理各种情况,仅仅参数值不同,所以,该中定义了三个属性来分别记住是哪种客户的哪种套餐下的哪种服务项,这样,要计算某种用户类型的某种套餐的某种业务功能的当月费用,只需要将这三个属性设置为相应的值即可。
2.如果VIP客户和common客户的不同套餐的每种服务费的算法公式区别很大,那就需要为每种客户的每种套餐的每种服务方式各设计一个子类,并将它们的共同之处抽象成为父类,譬如,定义PhoneComputeStrategy、MessageComputeStrategy、DataComputeStrategy等子类继承ComputeStragtegy。由于本系统可以采用同一种算法公式来处理各种情况,仅仅参数值不同,所以不需要采用多个子类的方式来做。

源码如下:

[c-sharp] view plaincopy
  1. public class ComputeStrategy {  
  2.     private int customerType;  
  3.     private int packType;  
  4.     private int businessType;  
  5.     private String businessName = "";  
  6.       
  7.     public ComputeStrategy(int customerType, int packType, int businessType) {  
  8.         this.customerType = customerType;  
  9.         this.packType = packType;  
  10.         this.businessType = businessType;  
  11.         switch(businessType){  
  12.             case 0:businessName = "电话";break;  
  13.             case 1:businessName = "短信";break;  
  14.             case 2:businessName = "数据";break;     
  15.         }         
  16.     }  
  17.       
  18.     public int computeMoney(int quantity){  
  19.         int price = ConfigManager.getPrice(customerType, packType,businessType);  
  20.   
  21.         int freeQuantity = ConfigManager.getFree(customerType, packType,businessType);  
  22.         int chargeQuantity = quantity - freeQuantity;  
  23.         if(chargeQuantity < 0){  
  24.             chargeQuantity = 0;  
  25.         }  
  26.         int phoneBaseMoney = ConfigManager.getRent(customerType, packType,businessType);      
  27.         System.out.print(businessName + "功能费:" + phoneBaseMoney + "厘钱,");                 
  28.         int fee = price * chargeQuantity;  
  29.         System.out.println(businessName + "计价费:" + quantity + "-" + freeQuantity + "=" + chargeQuantity + ","   
  30.                     + chargeQuantity + "*" + price + "=" + fee +"厘钱");  
  31.         return phoneBaseMoney + fee;  
  32.     }  
  33. }  

 

(十)Rent类(用于计算VIP用户月租费或月基本费)
1.VIP用户需要支付月租费或月基本费,如果是月租费,则还需要按照天来计算,这个计算相对来说也有一点复杂,为此,可以将计算月租费或月基本费的功能封装到一个Rent类中,这样对整个计算账单费用的程序模块来说,就不需要关心具体的计算细节了,只需要调用Rent类的实例对象即可得到用户要缴纳的月租费或月基本费。

源码如下:

 

[c-sharp] view plaincopy
  1. public class Rent {  
  2.     private int price;  
  3.     private RentUnit unit = RentUnit.MONTH;  
  4.       
  5.     public Rent(int price,RentUnit unit){  
  6.         this.price = price;  
  7.         this.unit = unit;  
  8.     }  
  9.       
  10.     public int coputeRent(Date startTime,Date currentMonth){  
  11.         //首先应该想到去找开源的日期运算类        
  12.         if(unit == RentUnit.DAY){  
  13.             Calendar start = Calendar.getInstance();  
  14.             start.setTime(startTime);  
  15.   
  16.             Calendar end = Calendar.getInstance();  
  17.             end.setTime(currentMonth);  
  18.             //将日期设置为当月的最后一天  
  19.             end.set(Calendar.DAY_OF_MONTH, 1);  
  20.             end.add(Calendar.MONTH, 1);  
  21.             end.add(Calendar.DAY_OF_MONTH, -1);  
  22.               
  23.             int days =  end.get(Calendar.DAY_OF_MONTH) ;  
  24.             if(end.get(Calendar.MONTH) == start.get(Calendar.MONTH)){  
  25.                 days -= start.get(Calendar.DAY_OF_MONTH) + 1;                 
  26.             }  
  27.   
  28.             return  price*days;  
  29.         }  
  30.         else{  
  31.             return price;  
  32.         }  
  33.     }     
  34. }  

Rent类中所使用的枚举类RentUnit非常简单,其中仅仅是定义了MONTH和DAY两个成员, 其源码如下:

[c-sharp] view plaincopy
  1. public enum RentUnit {  
  2.     DAY,MONTH;  
  3. }  

 

(十一)PackStrategy类(用于存储用户的各项业务套餐策略)
这个类中的程序代码的逻辑最为复杂,建议读者在阅读此类的代码之前,先思考清楚如下问题:
1.假如用户在2月时订购从3月以后的套餐,那么在结算2月份的费用时,不能使用订购的套餐计费方式,而应该使用原先的套餐计费方式;结算3月以后的费用时,就应采用订购的套餐计费方式了。显然,要处理某项业务功能的月账单费用,在PackStrategy中类中要为之存储两份ComputeStrategy对象,一份是原先或当前的套餐计费策略,另一份是订购的从某个月开始的套餐计费策略。
2.
问: 假设2月份的时候订3月以后的套餐, 2月底计算2月份的费用时用哪个套餐?3月底计算3月份的费用时用哪个套餐?
答: 2月底计算2月份的费用时用PackStrategy中的原先或当前的套餐计费策略, 3月底计算3月份的费用时用订购的套餐计费策略。
总结:当计算某月的账单费用时,是采用PackStrategy中的原先或当前的套餐计费策略,还是采用订购的从某个月开始的套餐计费策略呢?这就要看是在计算哪个月的账单费用了,如果“计算账单费用的当前年月份”大于或等于“订购的从某个月开始的套餐计费策略的起效年月份”,那么就要用订购的从某个月开始的套餐计费策略,否则,就采用PackStrategy中的原先或当前的套餐计费策略。
3.
问: 2月的初始计费策略为套餐0, 2月份的时候订3月以后的套餐1,3月份的时候又订4月以后的套餐2,请问,3月底计算3月份的费用时用哪个套餐?
答: 3月底计算3月份的费用时应该用套餐1。在程序代码中,在3月订4月的套餐2时,如果直接对订购变量进行赋值,它将冲掉 2月份订购的3月份以后的套餐1信息,而PackStrategy中的原先或当前的计费策略为套餐0,这样在3月底计算3月份的费用时,将得到错误的结果。所以,应该先将2月份订购的3月份以后的套餐1赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量,再用3月订4月的套餐2对订购变量赋值,这样在3月底计算3月份的费用时,采用PackStrategy中的原先或当前的套餐计费策略,正好就是2月份订购的3月份以后的套餐1。
4.
问: 2月的初始计费策略为套餐0, 2月份的时候订了3月以后的套餐1,随后,还是在2月份的时候又重新订购3月以后的套餐,改订为套餐2,请问,2月底计算2月份的费用时用哪个套餐?
答:还应该用2月的初始计费策略套餐0。也就是说,在2月份的时候又重新订购3月以后的套餐2时,应该直接对订购变量进行赋值,让它冲掉 2月份订购的3月份以后的套餐1信息,而不要将2月份订购的3月份以后的套餐1赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量,这一点与上面的情况正好不同。
总结:当重新订购新的套餐时,只有原来订购的套餐对当前的年月份起作用时(也就是 “订购变量中存储的日期”小于或等于当前的年月份,即“新订购的套餐的年月份”大于“订购变量中存储的日期”,因为订购的年月份总是当前月份基础上加1),原来订购的套餐信息才要赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量,以便计算当前月的费用时使用,否则,如果原来订购的套餐对当前的年月份是不起作用,那么,则不能将原来订购的套餐信息才要赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量, 让它直接被新订购的策略冲掉即可。
5.根据面向对象的封装特性,当我们订购新的计费策略时,原来订购的计费策略是否对当前月有效,即是否将原来订购的套餐信息赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量, 这个功能不是在PackStrategy类中完成,而是在订购记录对象中完成,因为原来订购的套餐策略的订购日期是存储在订购记录类中的。同样的道理,在计算某月的账单费用时,是否采用订购的从某个月开始的套餐计费策略,这一功能也是由订购记录类来提供。

源码如下:

[c-sharp] view plaincopy
  1. public class PackStrategy {  
  2.     private int customerType;  
  3.     private int packType = 0;  
  4.     private ComputeStrategy currentStrategies[] = new ComputeStrategy[3];  
  5.     private Rent rent;                                                                
  6.     private  OrderedStrategyHolder<ComputeStrategy> orderedStrategies[] = new OrderedStrategyHolder[]{  
  7.               new OrderedStrategyHolder<ComputeStrategy>(),    
  8.               new OrderedStrategyHolder<ComputeStrategy>(),  
  9.               new OrderedStrategyHolder<ComputeStrategy>(),  
  10.     };  
  11.     private OrderedStrategyHolder<Rent> orderedRent = new OrderedStrategyHolder<Rent>();  
  12.       
  13.     public PackStrategy(int customerType,int packType,Rent rent){  
  14.         this.customerType = customerType;  
  15.         this.packType = packType;  
  16.         this.rent = rent;  
  17.         for(int i=0;i<3;i++){  
  18.             currentStrategies[i] = new ComputeStrategy(customerType, packType,i);  
  19.         }  
  20.           
  21.     }  
  22.       
  23.     public Rent getValidRent(Date month){  
  24.         Rent validRent = orderedRent.getValidComputeStrategy(month);   
  25.         return validRent==null?rent:validRent;  
  26.       
  27.     }     
  28.       
  29.     public void orderRent(Date orderedMonth,Rent rent){  
  30.         Rent oldRent = orderedRent.order(orderedMonth, rent);  
  31.         if(oldRent != null){  
  32.             this.rent = oldRent;  
  33.         }     
  34.     }  
  35.   
  36.     public void cancelRent(Date orderedMonth,Rent rent){  
  37.         orderRent(orderedMonth,null);  
  38.     }     
  39.       
  40.     public ComputeStrategy getValidPhonePack(Date month){  
  41.         ComputeStrategy computeStrategy = (ComputeStrategy)orderedStrategies[0].getValidComputeStrategy(month);   
  42.         return computeStrategy==null?currentStrategies[0]:computeStrategy;  
  43.     }  
  44.   
  45.     public ComputeStrategy getValidMessagePack(Date month){  
  46.         ComputeStrategy computeStrategy = (ComputeStrategy)orderedStrategies[1].getValidComputeStrategy(month);   
  47.         return computeStrategy==null?currentStrategies[1]:computeStrategy;  
  48.     }  
  49.   
  50.     public ComputeStrategy getValidDataPack(Date month){  
  51.         ComputeStrategy computeStrategy = (ComputeStrategy)orderedStrategies[2].getValidComputeStrategy(month);   
  52.         return computeStrategy==null?currentStrategies[2]:computeStrategy;  
  53.     }     
  54.       
  55.     public void orderPhonePack(Date orderedMonth,int packType){  
  56.         ComputeStrategy oldComputeStrategy = orderedStrategies[0].order(orderedMonth, new ComputeStrategy(customerType, packType, 0));  
  57.         if(oldComputeStrategy != null){  
  58.             this.currentStrategies[0] = oldComputeStrategy;  
  59.         }  
  60.   
  61.     }  
  62.   
  63.     public void orderMessagePack(Date orderedMonth, int packType){    
  64.         ComputeStrategy oldComputeStrategy = orderedStrategies[1].order(orderedMonth, new ComputeStrategy(customerType, packType, 1));  
  65.         if(oldComputeStrategy != null){  
  66.             this.currentStrategies[1] = oldComputeStrategy;  
  67.         }  
  68.     }  
  69.   
  70.     public void orderDataPack(Date orderedMonth, int packType){  
  71.         ComputeStrategy oldComputeStrategy = orderedStrategies[2].order(orderedMonth, new ComputeStrategy(customerType, packType, 2));  
  72.         if(oldComputeStrategy != null){  
  73.             this.currentStrategies[2] = oldComputeStrategy;  
  74.         }  
  75.     }  
  76.   
  77.     public void cancelPhonePack(Date orderedMonth){  
  78.         orderPhonePack(orderedMonth, 0);  
  79.     }  
  80.       
  81.     public void cancelMessagePack(Date orderedMonth){  
  82.         orderMessagePack(orderedMonth, 0);    
  83.     }  
  84.       
  85.     public void cancelDataPack(Date orderedMonth){  
  86.         orderDataPack(orderedMonth, 0);  
  87.     }  
  88.       
  89. /*  public PhoneComputeStrategy getOrderedPhonePack(){ 
  90.         PhoneComputeStrategy phoneHolderStrategy = (PhoneComputeStrategy)phoneOrderedStrategyHolder.getOrderedStrategy();  
  91.         return phoneHolderStrategy; 
  92.     } 
  93.  
  94.     public MessageComputeStrategy getOrderedMessagePack(){ 
  95.         MessageComputeStrategy messageHolderStrategy = (MessageComputeStrategy)messageOrderedStrategyHolder.getOrderedStrategy();  
  96.         return messageHolderStrategy; 
  97.     } 
  98.      
  99.     public DataComputeStrategy getOrderedDataPack(){ 
  100.         DataComputeStrategy dataHolderStrategy = (DataComputeStrategy)dataOrderedStrategyHolder.getOrderedStrategy();  
  101.         return dataHolderStrategy; 
  102.     }   */  
  103. }  

 

(十二)OrderedStrategyHolder类(用于存储一项业务套餐订购信息)
1.用户订购一项业务功能套餐时需要记录生效的年月份和相应的业务功能套餐策略等两个信息,为此,需要设计一个订购记录类来管理这些信息,该类包含两个字段:套餐生效的年月份和订购的业务功能套餐策略。由于VIP用户订购套餐时,除了要记录各项业务功能的计费策略外,还要记录月租金或月基本费,月租金或月基本费的记录方式与记录一项业务功能的套餐方式完全一样,只是记录的参数类型不同,一个是ComputeStrategy策略对象,一个是Rent对象,所以,可以采用泛型技术来设计订购记录类,让它可以记录业务功能套餐策略的订购,也可以记录月租金或月基本费的订购。
2.本订购记录类中提供了一个order()方法来更新其中记录的套餐订购信息。前面讲解PackStrategy类的设计原理时已经提到过:因为原来订购的套餐策略的订购日期是存储在订购记录类中的,根据面向对象的封装特性,当我们订购新的计费策略时,原来订购的计费策略是否对当前月有效,即是否将原来订购的套餐信息赋值给PackStrategy中的用于记录原先或当前的套餐计费策略的变量, 这个功能不是在PackStrategy类中完成,而是在订购记录对象中完成。要防止设置下个月的计费策略时把当前月的计费策略冲掉,这个逻辑是在order方法中完成的,order方法中要根据原来记录的计费策略的生效年月份来判断是否要把原来记录的计费策略返回出去,如果原来记录计费策略的生效年月份已经是下个月了,则不能将此计费策略返回出去,这时候返回null,表示订购记录中原来存储的计费策略对当前月无效,PackStrategy类应使用其中的原先或当前的套餐计费策略的变量来计算当前月的费用,否则, PackStrategy类应使用order方法返回的计费策略对象来计算当前月的费用。
3. 在计算某月的账单费用时,是否采用订购的从某个月开始的套餐计费策略,同样还是根据面向对象的封装特性,这一功能也应由订购记录类来提供。所以,本订购记录类中提供了一个getValidStrategy()方法来判断其中记录的套餐是否对某月有效,如果有效则返回该套餐策略对象,否则返回null。

源码如下:

[c-sharp] view plaincopy
  1. public class OrderedStrategyHolder<T> {  
  2.     private Date orderedMonth;  
  3.     private T computeStrategy;  
  4.       
  5.     public T order(Date orderedMonth,T computeStrategy){  
  6.         T oldComputeStrategy = null;  
  7.         if(this.orderedMonth!=null && this.orderedMonth.before(orderedMonth)){  
  8.             oldComputeStrategy = this.computeStrategy;  
  9.         }  
  10.         this.orderedMonth = orderedMonth;  
  11.         this.computeStrategy = computeStrategy;  
  12.   
  13.         return oldComputeStrategy;  
  14.     }  
  15.       
  16.     public T getValidComputeStrategy(Date month){  
  17.         if(this.orderedMonth!=null && !month.before(orderedMonth)){  
  18.             return computeStrategy;  
  19.         }  
  20.         return null;  
  21.     }  


0 0
原创粉丝点击