Android's HandlerCaller - Decorator pattern

     Android's code base is a rich source for object oriented patterns. One such is the decorator pattern used in HandlerCaller. The Handler implementation had the support to send a message with a maximum of two integers and one Object type. But what if a component wanted to send more than one Object? Well, they could just nest all these types into a master type and handle the logic by themselves. And this additional functionality is what is decorated in HandlerCaller. Internally, it just uses SomeArgs to nest multiple objects and uses the standard Handler APIs. The only catch is that this is an internal API and can't be used via SDK.

    public Message obtainMessageIIOO(int what, int arg1, int arg2,
            Object arg3, Object arg4) {
        SomeArgs args = SomeArgs.obtain();
        args.arg1 = arg3;
        args.arg2 = arg4;
        return mH.obtainMessage(what, arg1, arg2, args);
    }
    
    public Message obtainMessageIOO(int what, int arg1, Object arg2, Object arg3) {
        SomeArgs args = SomeArgs.obtain();
        args.arg1 = arg2;
        args.arg2 = arg3;
        return mH.obtainMessage(what, arg1, 0, args);
    }
    
    public Message obtainMessageOO(int what, Object arg1, Object arg2) {
        SomeArgs args = SomeArgs.obtain();
        args.arg1 = arg1;
        args.arg2 = arg2;
        return mH.obtainMessage(what, 0, 0, args);
    }
    
    public Message obtainMessageOOO(int what, Object arg1, Object arg2, Object arg3) {
        SomeArgs args = SomeArgs.obtain();
        args.arg1 = arg1;
        args.arg2 = arg2;
        args.arg3 = arg3;
        return mH.obtainMessage(what, 0, 0, args);
    }

No comments: