Abstract method with variable list of arguments

前端 未结 5 1361
轮回少年
轮回少年 2021-02-05 07:09

I haven\'t quite found an elegant way to solve this issue. I have an abstract class that several other classes are inheriting with an abstract method that can contain anywhere f

5条回答
  •  梦如初夏
    2021-02-05 07:34

    What you want is the Value Object Pattern.

    Define a class that encapsulates the various parameter types into one value object, and have the abstract method accept a parameter of this type. Each variation of parameters you were considering would have its own value class.

    Then simply add a generic type to the class and have the abstract method accept a parameter of that type:

    public abstract class Item {
        public abstract void use(V v);
    }
    

    To use it, suppose MyItem needs a value object of type MyValueClass:

    public class MyItem extends Item {
        public void use(MyValueClass v) {
        }
    }
    

提交回复
热议问题