Java. How to set what a method can take as input from a given list (within the method)

38 views Asked by At

Is it possible to build a method that only accepts values from a given list of options? Something with a "behavior" similar to the setBackground method, which start displaying a default,

BorderPane bP = new BorderPane();
bP.setBackground(Background.EMPTY);

My goal is to build a factory class, which has a method that takes in either A, or B, or C and returns corresponding objects. The final result of what I am looking is would be something like:

MyObject square = new MyObjectFactory(SQUARE)// square is default and is added automatically to the method.
MyObject circle= new  MyObjectFactory(CIRCLE);//user gets a list of SQUARE, CIRCLE, or TRIANGLE... 

I tried to look on Stackoverflow for similar questions, but I am not even sure what the feature I am looking for is called to start with. So I am describing the "behavior", sort of.

Is there a way to make such a thing in JAVA, or is it only a JAVA "thing"? Any help is appreciated.

1

There are 1 answers

0
Jens-Peter Haack On BEST ANSWER

This could be a possible factory pattern for custom graphic objects:

enum ObjectType { CIRCLE, SQUARE };

public class MyObject extends Group {
}

public class MyCircle extends MyObject {
    public MyCircle() {
        getChildren().add(new Circle(12));
    }
}

public class MyRectangle extends MyObject {
    public MyRectangle() {
        getChildren().add(new Rectangle(0, 0, 18, 18));
    }
}

public class MyObjectFactory {
    static MyObject make(ObjectType type) {
        switch (type) {
            case CIRCLE: return new MyCircle();
            case SQUARE: return new MyRectangle();
            default: throw new UnsupportedOperationException("Unsupported type: "+type);
        }
    }
}

void testFactory(VBox box) {
    MyObject circle = MyObjectFactory.make(ObjectType.CIRCLE);
    MyObject square = MyObjectFactory.make(ObjectType.SQUARE);

    box.getChildren().addAll(circle, square);

}