IMAD UL-HASSAN
IMAD UL-HASSAN

Reputation: 71

What is Builder class in Android and what is its purpose?

I was working on NotificationManager but i can't understand the purpose of builder. Notification n = new Notification.Builder(this)

Upvotes: 4

Views: 8725

Answers (2)

Lakmal Fernando
Lakmal Fernando

Reputation: 1540

The builder is a pattern to create particular object (Notification, AudioFocusRequest etc..) therefore try to build your notification step by step as follows.

Notification noti = new Notification.Builder(mContext)
     .setContentTitle("New mail from " + sender.toString())
     .setContentText(subject)
     .setSmallIcon(R.drawable.new_mail)
     .setLargeIcon(aBitmap)
     .build();
  • You can find more information

about Builder: - https://www.tutorialspoint.com/design_pattern/builder_pattern.htm

about Notification.Builder : - https://developer.android.com/reference/android/app/Notification.Builder

Upvotes: 1

Mauker
Mauker

Reputation: 11497

Builder isn't something specific to the Android environment, as it is a design pattern. The Notification class just happens to use that pattern.

As you can see on the Notification docs:

The Notification.Builder has been added to make it easier to construct Notifications.

And that is what Builder is all about. To make things easier.

The sole purpose of such a pattern is to to separate the construction of a complex object from its representation. As stated on oopaterns website:

This pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the object's representation.

So instead of calling a constructor with a lot of arguments, you create a builder, and fine tune it with the parameters you need, then you'll call the build() method to create the object you need.

It also helps when you have predefined object templates, and you can use the builder pattern to instantiate such objects without having to pass arguments to it.

You can read more about that on this tutorial.

Upvotes: 6

Related Questions