fiz
fiz

Reputation: 936

Implementing this Interface Properly

I'm trying to implement this interface properly:

public interface OccupancyGrid {

    public Grid  grid();
}

Then I have a class which implements it:

    public class OccupancyCheckView implements OccupancyGrid{

    private Grid myGrid = new Grid(17,17);

    @Override
    public Grid grid() {

        return myGrid;
    }

    public main_(){
        createResultGrid("Test Grid");
                //More code below which changes the properties of 'myGrid'
    }

Then I have a class which is trying to call upon the above interface:

public class TestOccupanciesPanel
{
    private VerticalPanel mainPanel_;

        OccupancyGrid myGrid = new OccupancyCheckView();

    //This is where I trip up
        mainPanel_.add(myGrid);

I've seen elsewhere in the code I'm editing the user of interfaces very cleanly but without going about it in the way I've done above, it seems much cleaner. The code simply does something like:

OccupancyCheckView.class

Can you help me out and give me some tips?

Upvotes: 0

Views: 34

Answers (1)

hoefling
hoefling

Reputation: 66371

Either call your createResultGrid method in the constructor:

public OccupancyCheckView() {
     myGrid = new Grid(17,17);
     createResultGrid("Test Grid");
}

With this approach, the createResultGrid method will be executed on object creation - if you have some heavy code there, it might slow the program.

Or use lazy initialisation:

private boolean resultGridCreated = false;

@Override
public Grid grid() {
    if(!resultGridCreated) {
        createResultGrid("Test Grid");
        resultGridCreated = true;
    }
    return myGrid;
}

With this approach, the grid initialisation will be done the first time when grid() is being called.

Upvotes: 1

Related Questions