简体   繁体   English

如何根据 Java 中的构造函数参数声明具有不同类型的 class 字段

[英]How to declare class fields that have different types depending on the constructor parameters in Java

I'm new with Java and I'm trying to implement a class to encapsulate a clinic with a queue to determine the next patient to treat.我是 Java 的新手,我正在尝试实现 class 来封装一个带有队列以确定下一个要治疗的患者的诊所。

When initializing an instance of the class, I want to pass a triage type parameter to the constructor to decide how the clinic will select the next patient (frist in first out, or based on the gravity of the disease).在初始化 class 的实例时,我想将分类类型参数传递给构造函数,以决定诊所如何将 select 下一个患者(先入先出,或基于疾病的严重性)。 Concretely, I want to have a single queue class field that is going to either be a Queue or a PriorityQueue depending on the triage parameter.具体来说,我想要一个queue class 字段,该字段将是QueuePriorityQueue队列,具体取决于分类参数。 I have a hard time to figure how to declare the queue field.我很难弄清楚如何声明queue字段。

public enum TriageType {
    FIFO,
    GRAVITY
}

public class Clinic {

    public TriageType triageType;

    // This code block doesn't work, but it's the kind 
    // of behavior that I want
    if (triageType == TriageType.FIFO) {
        Queue<Patient> queue = new LinkedList<>()
    }
    else {
        PriorityQueue<Patient> queue = new PriorityQueue<>()
    }

    public Clinic(TriageType _triageType) {
        this.triageType = _triageType;
    }
}

Is it possible to do this without using two distinct classes?是否可以在不使用两个不同的类的情况下做到这一点?

Thanks a lot.非常感谢。

You cannot determine the static type of the field at runtime.您无法在运行时确定该字段的 static 类型。 Instead, you would use a common supertype, in this case Queue as the type.相反,您将使用一个常见的超类型,在本例中为Queue作为类型。

If that doesn't fit your needs, say if you need to use methods specific to PriorityQueue , the right solution would be to use polymorphism for this, declaring two separete classes, eg, FIFOClinic and GravityClinic , which both declare the queue as they require it.如果这不符合您的需求,比如说您需要使用特定于PriorityQueue的方法,那么正确的解决方案是为此使用多态性,声明两个单独的类,例如FIFOClinicGravityClinic ,它们都根据需要声明队列它。 The public methods that these classes would have in common should be extracted to a Clinic interface.这些类共有的公共方法应该被提取到Clinic接口。

While the Clinic interface can be used in all instances where the public methods are called, the two classes have to be explicitly referenced during construction.虽然Clinic接口可以在调用公共方法的所有实例中使用,但在构造过程中必须显式引用这两个类。 If you require the construction to be uniform, ie, depend only on a TriageType parameter, you could use the abstract factory pattern .如果您要求构造是统一的,即仅依赖于TriageType参数,您可以使用抽象工厂模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM