Java如何根据构造参数声明不同类型类字段?诊所队列实现疑问
解决方案
完全可以不用拆分两个类,利用Java的接口多态特性就能实现你的需求。核心思路是用Queue<Patient>作为统一的字段类型,因为LinkedList和PriorityQueue都实现了Queue接口,这样同一个字段可以引用不同的队列实例,再根据构造时传入的TriageType枚举来初始化对应的队列。
完整可运行代码
public enum TriageType { FIFO, GRAVITY } // 患者类,若使用病情优先模式,需要支持排序 class Patient implements Comparable<Patient> { private String name; private int severity; // 数值越大表示病情越严重 public Patient(String name, int severity) { this.name = name; this.severity = severity; } // 实现Comparable接口,定义病情优先级排序规则(严重者优先) @Override public int compareTo(Patient other) { return Integer.compare(other.severity, this.severity); } // 可选:重写toString方便调试输出 @Override public String toString() { return name + " (病情等级:" + severity + ")"; } // 若用外部比较器,需要提供getter方法 public int getSeverity() { return severity; } } public class Clinic { private final Queue<Patient> queue; private final TriageType triageType; public Clinic(TriageType triageType) { this.triageType = triageType; // 根据分诊类型初始化对应队列 if (triageType == TriageType.FIFO) { this.queue = new LinkedList<>(); } else { // 两种初始化PriorityQueue的方式选其一即可 // 方式1:依赖Patient实现的Comparable接口 this.queue = new PriorityQueue<>(); // 方式2:传入自定义比较器(无需Patient实现Comparable) // this.queue = new PriorityQueue<>((p1, p2) -> Integer.compare(p2.getSeverity(), p1.getSeverity())); } } // 新增患者到队列 public void registerPatient(Patient patient) { queue.offer(patient); } // 获取下一位就诊患者(队首元素出队) public Patient getNextPatient() { return queue.poll(); } // 测试示例 public static void main(String[] args) { // FIFO模式测试 Clinic walkInClinic = new Clinic(TriageType.FIFO); walkInClinic.registerPatient(new Patient("张三", 1)); walkInClinic.registerPatient(new Patient("李四", 3)); walkInClinic.registerPatient(new Patient("王五", 2)); System.out.println("FIFO分诊顺序:"); Patient patient; while ((patient = walkInClinic.getNextPatient()) != null) { System.out.println(patient); } // 病情优先模式测试 Clinic emergencyClinic = new Clinic(TriageType.GRAVITY); emergencyClinic.registerPatient(new Patient("张三", 1)); emergencyClinic.registerPatient(new Patient("李四", 3)); emergencyClinic.registerPatient(new Patient("王五", 2)); System.out.println("\n病情优先分诊顺序:"); while ((patient = emergencyClinic.getNextPatient()) != null) { System.out.println(patient); } } }
核心说明
- 统一字段类型:用
Queue<Patient>声明队列字段,这是LinkedList和PriorityQueue的共同接口,实现了多态引用,避免了单独声明两个字段的麻烦。 - 构造时初始化:在Clinic的构造方法中根据传入的
TriageType,选择实例化对应的队列实现类,逻辑清晰且符合需求。 - PriorityQueue排序:如果使用病情严重程度排序,有两种方式:
- 让
Patient类实现Comparable<Patient>接口,定义默认排序规则; - 初始化
PriorityQueue时传入自定义Comparator,这种方式不需要修改Patient类,灵活性更高。
- 让
- 封装性优化:把队列和分诊类型设为
private final,只通过公共方法操作队列,避免外部直接修改内部状态,符合面向对象的封装原则。
内容的提问来源于stack exchange,提问作者jimrustle
相关产品推荐
相关产品推荐

