3

I have multiple objects in an inheritance structure like this:

public class ImageButton extends JButton {
    private Image image;

    public ImageButton(Image i) {
        this.image = i;
    }
}

public class ColorButton extends JButton {
    private Color color;

    public ColorButton(Color c) {
        this.color = c;
    }
}

All objects extend JButton. There are more complex objects that extend the ImageButton class and so on. I thought to use Abstract Factory Pattern, but my problem is, that the constructors take different attributes for each class.

Which pattern can I use to realize a good way of creation?

2
  • You can assign SubClass object to SuperClass. while using methods of SubClass typecast object to specific and access those method. Commented Apr 23, 2020 at 7:38
  • I am looking for a fitting design pattern that I can use to create them, what do you mean? Commented Apr 23, 2020 at 7:48

1 Answer 1

4

You can use static factory methods for this. An example I can point to for inspiration here is guava's Lists, which defines, among other factories

  • newArrayList(E... elements) (array list with given elements)
  • newArrayListWithCapacity(int initialArraySize) (empty array list with capacity)
  • newLinkedList() (empty linked list)
  • ...

That's based on the understanding that you want to simplify the creation of your button objects, for which I think static factory methods are a good fit.

Your own code could include such methods as (in the same class, or even interface):

public static JButton imageButton(Image i) {
    return new ImageButton(i);
}
public static JButton colorButton(Color color) {
    return new ColorButton(color);
}
public static JButton greenButton() {
    return new ColorButton(Color.GREEN);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I thought of this solution already but I also thought that there must be some different pattern, because the objects are all extending JButton. Guess I am creating a static factory. Thank you!
@F_Schmidt I noted that I supposed you needed to simplify the code needing to create buttons. If that's the case, then this kind of static factory can work well, in my opinion at least. If your objective is to take the responsibility of picking the exact button implementation from callers, then this implementation doesn't quite work.
I want to hide the classes and therefore want simple calls when I create a Button of any type. I do not want to have calls like ColorButton c = new ColorButton(...) or even ColorTextButton ct = new ColorTextButton("...", ...); But having calls like ButtonFactory.create(...) or createColorButton(...) is more neat in my oppinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.