Search code examples
javaandroidclassdelegatesdemo

Why does the Android maps compass demo use a delegate for the SmoothCanvas class?


In the Android MapsDemo available in Eclipse for the Google API, they create an inner class SmoothCanvas in MapViewCompassDemo.java. Within this class the re-implement seemingly every method and reroute it to a delegate instance of Canvas.

static final class SmoothCanvas extends Canvas {
    Canvas delegate;

    private final Paint mSmooth = new Paint(Paint.FILTER_BITMAP_FLAG);

    public void setBitmap(Bitmap bitmap) {
        delegate.setBitmap(bitmap);
    }

    public void setViewport(int width, int height) {
        delegate.setViewport(width, height);
    }
    ...

What is the point of the delegate in this instance?


Solution

  • The value of delegate is passed in to dispatchDraw. The SmoothCanvas class is a wrapper around delegate. By delegating, the Canvas implementation passed to dispatchDraw does all the heavy lifting. The wrapper just allows the injection of the smoothed paint without implementing all the logic of Canvas.