Sobes.tech
Middle

Can you tell me about some 'builder' design patterns in Android?

sobes.tech AI

Answer from AI

The "Builder" pattern is used for creating complex objects step by step.

Examples of usage in Android:

  1. AlertDialog.Builder: Creating dialogs with options to specify title, message, buttons, and other properties.

    new AlertDialog.Builder(context)
        .setTitle("Title")
        .setMessage("Message text")
        .setPositiveButton("OK", (dialog, which) -> {
            // Action upon OK click
        })
        .setNegativeButton("Cancel", null)
        .show();
    
  2. NotificationCompat.Builder: Building notifications for the status bar.

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Notification title")
        .setContentText("Notification text")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    
    Notification notification = builder.build();
    // Sending notification via NotificationManager
    
  3. Uri.Builder: Creating a URI with various parameters.

    Uri builtUri = new Uri.Builder()
        .scheme("http")
        .authority("www.example.com")
        .appendPath("path")
        .appendQueryParameter("param1", "value1")
        .build();
    
  4. ViewModelProvider.Builder: (In Lifecycle Architecture Components) Building a factory for ViewModel.

    ViewModelProvider provider = new ViewModelProvider(activity, new ViewModelProvider.AndroidViewModelFactory(application));
    MyViewModel viewModel = provider.get(MyViewModel.class);
    

Main advantages of using the builder:

  • Improves code readability when creating objects with many optional parameters.
  • Avoids creating multiple constructors.
  • Provides step-by-step object construction.
  • The object is created only after calling the build() method.
Can you tell me about some 'builder' design patterns… - sobes.tech