表驱动模式
从表中查找数据而不是使用if-else,数组,map等实现。
v2ex上讨论使用表驱动案例
使用hashmap进行类型判断代替if-else类型判断,使用空间换时间,增强代码可维护性
使用枚举,链表实现表驱动模式
package com.lize;
import java.util.ArrayList;
import java.util.List;
public class TableDriveDemo {
public static void main(String[] args) {
System.out.println(Date.getTeachersName(CLASS.CLASSA, COURSE.English));
System.out.println(Date.getTeachersName(CLASS.CLASSA, COURSE.Math));
System.out.println(Date.getTeachersName(CLASS.CLASSB, COURSE.English));
System.out.println(Date.getTeachersName(CLASS.CLASSB, COURSE.Math));
}
}
enum CLASS{
CLASSA,
CLASSB;
}
enum COURSE{
English,
Math;
}
class ClassAndCourse{
CLASS cls;
COURSE course;
String teacherName;
public ClassAndCourse(CLASS cls, COURSE course, String teacherName) {
this.cls = cls;
this.course = course;
this.teacherName = teacherName;
}
}
class Date{
static List<ClassAndCourse> list = new ArrayList<>();
static {
list.add(new ClassAndCourse(CLASS.CLASSA, COURSE.English, "小王"));
list.add(new ClassAndCourse(CLASS.CLASSA, COURSE.Math, "小张"));
list.add(new ClassAndCourse(CLASS.CLASSB, COURSE.English, "也是小王"));
list.add(new ClassAndCourse(CLASS.CLASSB, COURSE.Math, "小李"));
}
public static String getTeachersName(CLASS cls,COURSE course) {
String name = null;
for(ClassAndCourse x:list) {
if(x.cls.equals(cls) && x.course.equals(course)) {
name = x.teacherName;
break;
}
}
return name;
}
}
表驱动统计字符串中首次出现频率最高的数字
表驱动三种索引方式:直接索引、索引表、阶梯索引
public static char statMostRateChar(String str) {
if (str != null && !"".equals(str)) {
int charsStat[] = new int[128];
int charsFirstIdx[] = new int[128];
int strLen = str.length();
for (int ch = 0; ch < 128;ch++) {
charsFirstIdx[ch] = strLen;
}
// 統計字符出現的次數
for (int idx = 0; idx < strLen; idx++) {
charsStat[str.charAt(idx)]++;
// 记录字符第一次出现的位置
if (idx < charsFirstIdx[str.charAt(idx)]) {
charsFirstIdx[str.charAt(idx)] = idx;
}
}
int mostRateChar = 0;
for (int ch = 1; ch < 128; ch++) {
if (charsStat[ch] == 0) {
continue;
}
// 找频率出现最高的字符
if (charsStat[mostRateChar] < charsStat[ch]) {
mostRateChar = ch;
// 出现频率一样时,选择出现在前面的数
} else if (charsStat[mostRateChar] == charsStat[ch]&&
charsFirstIdx[mostRateChar] > charsFirstIdx[ch]) {
mostRateChar = ch;
}
}
return (char) mostRateChar;
} else {
return '\0';
}
}