Skip to content
Advertisement

Using Inheritance like this is right?

I’m student learning Inheritance in Java.

I’m making a program (Bitcoin Mining Game). In the program, there are different kind of digger (Mining Machine):

  • ordinary digger (this only does digging coin),

  • overclock digger (this can dig and can overclock to dig faster) and

  • durability recover digger (this can dig, overclock and recover durability (every digger has durability, durability drops while digging).

I made this class diagram (There are some attributes and methods that I didn’t describe in pictures. I thought those are not needed for my question.):

enter image description here

I’m not sure that I did it right, in particular, the use if Inheritance.

Instead of using inheritance, should I just make a class like this? Because only one function adds to the classes:

enter image description here

Advertisement

Answer

This might be a good candidate for the Decorator Pattern, which allows you to apply customized functionality to an individual object at run time. A good reference for this can be found on the Decorator Pattern Wikipedia page, which includes a detailed example of a Windowing system, with a UML class diagram for reference. A snippet of the code shows the decorator and the concrete decorator:

// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
    private final Window windowToBeDecorated; // the Window being decorated

    public WindowDecorator (Window windowToBeDecorated) {
        this.windowToBeDecorated = windowToBeDecorated;
    }
    @Override
    public void draw() {
        windowToBeDecorated.draw(); //Delegation
    }
    @Override
    public String getDescription() {
        return windowToBeDecorated.getDescription(); //Delegation
    }
}

// The first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
    public VerticalScrollBarDecorator (Window windowToBeDecorated) {
        super(windowToBeDecorated);
    }

    @Override
    public void draw() {
        super.draw();
        drawVerticalScrollBar();
    }

    private void drawVerticalScrollBar() {
        // Draw the vertical scrollbar
    }

    @Override
    public String getDescription() {
        return super.getDescription() + ", including vertical scrollbars";
    }
}

In your case the decorator would be called DiggerDecorator and the concrete decorators could be called OverclockDecorator and RecoverDurabilityDecorator.

The code to instantiate a fully decorated object might look like this:

Digger decoratedDigger = new OverclockDecorator(new RecoverDurabilityDecorator(new SimpleDigger()));

As you can see, this solution still uses inheritance, but individual functionality can be “mixed in” as needed.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement