'VB示例:确定各月天数的笨拙做法 If (month = 1) Then days = 31 ElseIf (month = 2) Then days = 28 ElseIf (month = 3) Then days = 31 ... ElseIf (month = 11) Then days = 30 ElseIf (month = 12) Then days = 31 EndIf
每一条消息都有若干字段,并且每条消息都有一个消息头,其中有一个 ID ,告诉你该消息属于这 20 多种消息中的哪一种。
这些消息的格式并不是固定不变的消息的存储方式消息头(ID 确定了该消息所属的类型)
消息的存储方式
消息的格式细节
基于逻辑的方法
读取每一条消息,检查其 ID,然后调用一个用来阅读、解释以 及打印一种消息的子程序
消息阅读子程序包含一个循环,用来读入消息、解释其 ID,以及根据该 ID 调用 20 个子程序中的某一个
如果你有 20 种消息,那么就要有 20 个子程序
每次有任何一种消息的格式变了,你就不得不修改负责 处理该消息的子程序或者类的逻辑
基于逻辑方法所用的伪代码
1 2 3 4 5 6 7 8 9 10 11 12
While more messages to read Read a message header Decode the message ID from the message header If the message header is type 1 then Print a type 1 message Else if the message header is type 2 then Print a type 2 message ... Else if the message header is type 19 then Print a type 19 message Else if the message header is type 20 then Print a type 20 message
如何修改?将动作存储到表中可以将子程序入口地址存储,类似的有多态的实现
画向对象的方法
但是基本结构还是同样复杂
问题的逻辑可以隐藏在对象继承结构里
1 2 3 4 5 6 7 8 9 10 11 12 13 14
While more messages to read Read a message header Decode the message ID from the message header If the message header is type 1 then Instantiate a type 1 message object Else if the message header is type 2 then Instantiate a type 2 message object ... Else if the message header is type 19 then Instantiate a type 19 message object Else if the message header is type 20 then Instantiate a type 20 message object End if End While
读取和打印浮标温度消息子程序
表驱动法
消息阅读子程序由一个循环组成,该循环负责读入每一个消息头,对其 ID 解码,在 Message 数组中查询其消息描述,然后每次都调用同一个子程序来解释该消息
While more messages to read Read a message header Decode the message ID from the message header Look up the message description in the message-description table Read the message fields and print them based on the message description End While
消息打印子程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
While more fields to print Get the field type from the message description case ( field type ) of ( floating point ) read a floating-point value print the field label print the floating-point value of ( integer ) read an integer value print the field label print the integer value of ( character string ) read a character string print the field label print the character string ... End Case End While
' set up data for grading table Dim rangeLimit() AsDouble = { 50.0, 65.0, 75.0, 90.0, 100.0 } Dim grade() AsString = { "F", "D", "C", "B", "A" } maxGradeLevel = grade.Length - 1 ... ' assign a grade to a student based on the student's score gradeLevel = 0 studentGrade = "A" While ( gradeLevel < maxGradeLevel ) If ( studentScore < rangeLimit( gradeLevel ) ) Then studentGrade = grade( gradeLevel ) EndIf gradeLevel = gradeLevel + 1 Wend