Builder Pattern In Android
When I started with android, I almost always asked Google how to do the smallest things. I want to highlight the examples I found for starting an activity.
I always wondered why many examples used a variable called intent. You could easily create the Intent on-the-fly in the startActivity() parameter. Maybe it looks better, if you need to add some parameters to the intent like this?
But then again, the method putExtra() returns an Intent. As described in the example for method-chaining, such chaining can be relatively useful. Androids call to startActivity() could be rewritten to this:
Since this doesn’t need a variable, I like that approach more. In Android, this pattern is used quite often. The so called builder-pattern is used with AlertDialog for example. When built, you use the create() method in order to show the dialog itself (equals the build() method of the builder-pattern). To create URIs one can use the buildUpon() method to get a Uri.Builder. There are tons of other examples where Android uses such builders. Intents seem to be an exception, since there is no startActivity() function or similar to it. Returning the object itself was not even done consequently, to make chaining of some methods impossible. Examples for these are setSourceBounds() or setExtrasClassLoader().
I see two options to address these problems:
- Creation of a sub-class of Intent, which provides a startAsActivity() function. It needs to return its own type in every putExtra() method, to preserve the startAsActivity() method. This class could look like this:
The problem with this class is, that methods like public void setExtrasClassLoader() cannot be changed to return the BuilderIntent type.
- An alternative would be the usage of an external builder, which uses its own Intent internally. Take all functions you want to provide and change them for your requirements, somehow similar to the Decorator-Pattern.
The advantage is that you can setup a public ActivityBuilder setExtrasClassLoader() method without hassle. The problem is, that you cannot use methods from Intent at all. With the first option, that would be cumbersome but at least possible.
What I wanted to say is that a method like startAsActivity() seems to be missing. However, you can create your own builders around existing classes.
推荐一个用了一年多的理财「友金所」，小道消息、MacTalk、可能吧等公号均推荐过，绝对靠谱，新手年化收益 12% 及 166 元红包。点这里开始投资