You need to enable JavaScript to run this app. Java中如何实现不同类对象间消息传递及Patient类添加预约方法
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何实现不同类对象间消息传递及Patient类添加预约方法

实现Patient类发起预约创建Appointment实例的方案

前置修复:现有代码的隐藏问题

你目前提供的两个类的构造方法存在参数赋值错误,都是把固定字符串赋值给成员变量,没有使用传入的参数值,先修正避免后续逻辑出错:

修正后的Patient构造方法

public Patient (int id, String name, int age, String condition)
{
    this.setId(id);
    this.setName(name); // 改为传入的name参数,不是固定字符串"name"
    this.setAge(age);
    this.setCondition(condition); // 改为传入的condition参数,不是固定字符串"condition"
}

修正后的Appointment构造方法

public Appointment (int appointId, String date, String purpose)
{
    this.setAppointId(appointId);
    this.setDate(date); // 改为传入的date参数,不是固定字符串"date"
    this.setPurpose(purpose); // 改为传入的purpose参数,不是固定字符串"purpose"
}
// 建议补充Appointment类的getter方法,方便后续拿取预约信息
public int getAppointId() {
    return this.appointId;
}
public String getDate() {
    return this.date;
}
public String getPurpose() {
    return this.purpose;
}

核心实现:在Patient类添加预约挂号方法

根据业务需求可以选择两种实现方式:

方式1:方法直接返回新创建的Appointment实例

适合需要外部直接拿到预约对象做后续处理的场景,代码如下:

// 新增到Patient类中
public Appointment createAppointment(int appointId, String date, String purpose) {
    // 可以自动拼接患者基础信息到预约备注里,不需要调用方额外传
    String fullPurpose = String.format("患者ID:%d,患者姓名:%s,年龄:%d,症状:%s | 预约需求:%s",
            this.getId(), this.getName(), this.getAge(), this.getCondition(), purpose);
    return new Appointment(appointId, date, fullPurpose);
}

调用示例:

public class Main {
    public static void main(String[] args) {
        Patient patient = new Patient(1, "张三", 28, "反复咳嗽3天");
        // 患者实例调用预约方法,直接生成对应的Appointment实例
        Appointment appointment = patient.createAppointment(2024052001, "2024-05-20 09:30", "呼吸科普通号");
        System.out.println(appointment.getPurpose());
    }
}

方式2:Patient内部维护预约列表,记录患者所有预约记录

适合需要留存同一个患者所有历史预约的场景,代码如下:

// 先在Patient类的成员变量中新增预约列表
private List<Appointment> appointmentList = new ArrayList<>();

// 新增预约方法
public void addAppointment(int appointId, String date, String purpose) {
    String fullPurpose = String.format("患者ID:%d,患者姓名:%s,年龄:%d,症状:%s | 预约需求:%s",
            this.getId(), this.getName(), this.getAge(), this.getCondition(), purpose);
    Appointment newAppointment = new Appointment(appointId, date, fullPurpose);
    this.appointmentList.add(newAppointment);
}

// 新增获取所有预约的方法
public List<Appointment> getAppointmentList() {
    return this.appointmentList;
}

扩展:其他类实例通信的通用逻辑

你提到的Receptionist给Doctor发消息的需求,遵循同样的实现思路:在发送方的类中定义方法,将接收方实例作为参数传入,再调用接收方暴露的公共方法即可,比如:

// 在Doctor类中新增接收通知的方法
public void receiveNotification(String msg) {
    System.out.println("医生收到通知:" + msg);
}

// 在Receptionist类中新增通知医生的方法
public void notifyDoctor(Doctor doctor, String notification) {
    doctor.receiveNotification(notification);
}

内容的提问来源于stack exchange,提问作者Celestine Akpanoko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 11:09:03