Monday, February 24, 2014

Structural Relationship between Content Resolver and Content Provider - an example of Proxy Design Pattern...

As i was digging into the source code of Content Provider and Content Resolver, i found a nice structural relationship among the two and it closely resembles the Proxy Pattern of the GoF book. We need Proxy Pattern whenever there is a need of a sophisticated reference to an object other than the simple pointer.

The class diagram of the Proxy Pattern is something similar to the following:

What it actually does is that it adds a level of indirection when accessing an object. Whenever a client needs to interact with an object of a RealSubject, it instead interacts with a Proxy of it. The proxy forwards the request to the RealSubject.

Now let us dig into the source code of Content Resolver and Content Provider to understand how it resembles the Proxy Pattern. The Content Provider offers the client of it all of the CRUD (create, read, update & delete) functionalities. Internally what it does it forwards these functionalities to the Content Provider. There is an one to one mapping between the CRUD functions of the Content Resolver with the Content Providers. A simplistic version of the structural relationship between the Content Resolver and the Content Provider can be depicted as follows.

Whenever the client calls any of the above functions on the ContentResolver, it just gets a reference to the appropriate Content Provider by the function called aquireProvider and then delegates that function to that of the ContentProvider. In each of these CRUD functions, the ContentResolver also manages the lifecycle of the ContentProvider it acquires through a function called releaseProvider.

Thus we can say that to a client, the ContentResolver works as a proxy of ContentProviders.

No comments: