Sitemap
Abhishek Rai

Abhishek Rai

Design Pattern

16 min readAug 20, 2024

--

Design patterns are reusable solutions to common problems in software design. They represent best practices used by experienced object-oriented software developers.

Design patterns are not code, but instead are like descriptions on tackling certain software problems and designing a solution. It’s dot not suggest a direct solution implementation for the software problem at hand, but are an outline of a structure that could be used as per the needs of the problem.

Design patterns are valuable approach/practices for solving recurring problems and improving software design, but they should be used thoughtfully. The key is to understand when a pattern is appropriate and to apply it in a way that truly benefits the codebase.

Simple Explanation Using Cooking Analogies

Imagine you’re baking cookies. To make your baking process easier with best looks & test, you might use some special techniques that help you achieve the perfect cookies every time.

Software design patterns are like those baking techniques, but for programming. They are tried-and-true ways to solve common problems when building software. Instead of reinventing the wheel every time you face a problem, you use these patterns to make your coding more efficient and your software easier to maintain.

  1. Recipe (Design Pattern): Just like a recipe guides you on how to mix ingredients to bake cookies, a design pattern guides you on how to solve a common programming problem.
  2. Baking Techniques (Creational Patterns): Think of these as methods for preparing ingredients. For example, if you always use a specific method to mix flour and sugar, that’s similar to a creational pattern, which helps you create objects in a consistent way.
  3. Cookie Decorating (Structural Patterns): Once your cookies are baked, you might decorate them in different ways. Structural patterns help you organize and connect different parts of your software, just like how you decide how to decorate each cookie.
  4. Taste Testing (Behavioral Patterns): Finally, you taste the cookies to make sure they’re good. Behavioral patterns are like testing the cookies — they help ensure that different parts of your program work well together and do their jobs correctly.

Types of Design Patterns

There are three types of Design Patterns,

  1. Creational Design Pattern
  2. Structural Design Pattern
  3. Behavioral Design Pattern
Press enter or click to view image in full size

Image Credit Go to: Scaler.com

Pro and Cons

Pros of Design Patterns

  • Reusability: Design patterns promote code reuse by providing standardized solutions to common problems.
  • Maintainability: Code structured around design patterns is generally easier to maintain. Patterns help in organizing code logically, making it simpler to understand and modify.
  • Scalability: Design patterns often make your code more scalable. For example, patterns like Singleton or Factory can easily be adapted to handle more complex scenarios as your application grows.

Cons of Design Patterns

  • Overhead: Sometimes, using a design pattern can introduce unnecessary complexity and overhead.
  • Increased Code Size: Implementing design patterns often requires more code, which can lead to larger codebases.
  • Steep Learning Curve: Some patterns can be difficult to understand and implement correctly, particularly for junior developers. Misusing a pattern can lead to poor design rather than improvements.

Creation Design Pattern:

This patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

Creational Design Pattern abstract the instantiation process. They help in making a system independent of how its objects are created, composed and represented.

Types of Creational Design Patterns:

  1. Singleton: It ensures a class only has one instance
  2. Builder: It is used to construct a complex object step by step
  3. Factory Method: Creating objects without specifying the exact class of object that will be created
  4. Abstract Factory: Instantiates various families of classes
  5. Object Pool: Used when initialization cost of class is high
  6. Prototype: Used when time taken to create object is large and costly. Objects are created with existing object itself.

Singleton:

The Singleton Design Pattern is used to ensure that a class has only one instance and provides a global point of access to that instance. Useful when coordination of actions across the system can be done by exactly one object.

Example: Singleton, Object, Retrofit & RoomDB/Database connection or any class which will be used in entire application with single instance.

//Java Example
public class ApiClient {
private static Retrofit retrofit = null;

public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}


//Kotlin Example
object ApiClient {
private var retrofit: Retrofit? = null
private const val BASE_URL = "https://api.example.com/"

fun getClient(): Retrofit {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
}
/*
In Kotlin, the object keyword is used to create a singleton. This ensures that the ApiClient class has only one instance throughout the app’s lifecycle.
The object keyword automatically handles the creation of the instance and makes the ApiClient class thread-safe.
*/

Why to use Singleton Design Pattern

  1. Controlled Access to a Single Instance: In some situations, it’s essential to have only one instance of a class. For example, a class that manages a connection to a database or handles logging should be unique to ensure consistent access and prevent conflicting operations.
  2. Global Access Point: The Singleton pattern provides a single, globally accessible instance of a class. This is helpful for scenarios where various parts of an application need to share the same resource or configuration.
  3. Prevents Resource Wastage: By ensuring that only one instance exists, the Singleton pattern prevents the wastage of resources that could occur if multiple instances of a resource-heavy class were created.

Builder

Separates the object construction from it’s representations and It is used to construct a complex object step by step and the final step will return the object. Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
Example: AlertDialog.Builder, NotificationCompat.Builder

//Java Example
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Dialog Title")
.setMessage("This is a message")
.setPositiveButton("OK", null)
.setNegativeButton("Cancel", null)
.create();



//Kotlin Example
val dialog = AlertDialog.Builder(context)
.setTitle("Dialog Title")
.setMessage("This is a message")
.setPositiveButton("OK", null)
.setNegativeButton("Cancel", null)
.create()

Example: Own / Custom Builder Design with Mandatory, Option property & Callback

class FoodOrder private constructor(
val bread: String, // Mandatory
val condiments: String?,
val meat: String?,
val fish: String?) {

data class Builder(
var bread: String? = null,
var condiments: String? = null,
var meat: String? = null,
var fish: String? = null,
private var callback: ((String) -> String)? = null // Callback accepts and returns a string
) {

// Set the callback
fun onBuild(callback: (String) -> String) = apply { this.callback = callback }


fun bread(bread: String) = apply { this.bread = bread }
fun condiments(condiments: String) = apply { this.condiments = condiments }
fun meat(meat: String) = apply { this.meat = meat }
fun fish(fish: String) = apply { this.fish = fish }



fun randomBuild() = bread(bread!!)
.condiments(condiments ?: "pepper")
.meat(meat ?: "beef")
.fish(fish?: "Tilapia")
.build("your food")


fun build(message: String): String {
val foodOrder = FoodOrder(bread!!, condiments, meat, fish)
val inputMessage = "FoodOrder created with bread: ${foodOrder.bread}, condiments: ${foodOrder.condiments}, meat: ${foodOrder.meat}, fish: ${foodOrder.fish}. Message: $message"
return callback?.invoke(inputMessage)
?: "Callback not set. FoodOrder built with default handling."
}
}
}
val foodOrder = FoodOrder.Builder()
.bread("white bread") //Mendatory field
.meat("bacon") //Optiona field
.condiments("olive oil") //Optiona field
.onBuild { it -> // Log the input message
println("Callback processed: $it")
"Callback completed successfully" // Return a string
}
.build("Ny Food")

val rendomOrder = FoodOrder.Builder()
.bread("White") //Mendatory field
.onBuild { it -> // `it` is the input string
"Callback processed: $it"
}
.randomBuild() ////Optiona field
class Car( //add private constructor if necessary
val model: String?,
val year: Int,
var mobNo: Int,
var address: String //mendatory
) {


private constructor(builder: Builder) : this(builder.model, builder.year, builder.mobNo, builder.address!!)

class Builder(val mobNo: Int) {
var model: String? = null
private set

var year: Int = 0
private set

var address: String? = null //Nullable to enforce mandatory method call



fun model(model: String) = apply { this.model = model }

fun year(year: Int) = apply { this.year = year }

// Mandatory method for setting mobNo
fun address(address: String) = apply { this.address = address }


fun build(): Car {
// Check if mobNo was set; throw exception if not
if (address == null) {
throw IllegalStateException("address must be set before building a Car")
}
return Car(this)
}
}
}
  Car.Builder(2)
.address("My Add")
.build()

Why to use Builder Design Pattern

  1. Managing Complex Object Creation: When an object requires many optional parameters or when its construction process involves multiple steps, using constructors with numerous parameters can lead to confusion and errors. The Builder pattern helps break down the construction process into more manageable steps.
  2. Improving Code Readability: A long list of parameters in a constructor can be difficult to read and understand, especially if some parameters are optional. The Builder pattern creates a more readable way to instantiate objects, with method names clearly indicating what each step does.
  • Example: Compare a constructor like Car("red", 4, true, "electric", "sedan") with a builder approach: CarBuilder().setColor("red").setWheels(4).setElectric(true).setType("sedan").build(). The latter is much easier to read and understand.

Factory Method

The Factory Method pattern is used to create objects without specifying the exact class of object that will be created. This pattern is useful when you need to decouple the creation of an object from its implementation.

The Factory Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Simple Explanation: It’s like a factory in the real world that produces products, but you can customize what type of product it makes. Means that :=> Imagine you own a toy factory. You might have different types of toys: cars, dolls, and robots. Instead of creating each toy manually every time you need one, you set up a production line (factory) that can produce any type of toy based on your requirements. You just tell the factory, “Make me a toy,” and the factory decides which specific toy to create based on your order.

Like — In Android, the ViewModelProvider.Factory is an example of the factory pattern. When creating a ViewModel, you can use a factory to ensure the right type of ViewModel is created based on the context or parameters provided. This avoids the need to manually create ViewModel instances throughout your app, centralizing the creation logic.

Example: ViewModelProvider.Factory, Intent, FragmentFactor

//Java Example
public class MyViewModelFactory implements ViewModelProvider.Factory {
private final Repository repository;


@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new MyViewModel(repository);
}

public MyViewModelFactory(Repository repository) {
this.repository = repository;
}
}



//Kotlin Example
class MyViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {

@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MyViewModel(repository) as T
}
}
/*
ViewModelProvider.Factory: This indicates that MyViewModelFactory implements the ViewModelProvider.Factory interface.
The create method is overridden to return an instance of MyViewModel. The as T cast is necessary because the method returns a generic type T
*/

Example: Custom View Factory

Get Abhishek Rai’s stories in your inbox

Join Medium for free to get updates from this writer.

Imagine you are creating different types of buttons (PrimaryButton, SecondaryButton, etc.) dynamically at runtime.
Define a Button Interface:

interface Button {
fun render()
}
//Concrete Implementations:

class PrimaryButton : Button {
override fun render() {
println("Rendering a Primary Button")
}
}


class SecondaryButton : Button {
override fun render() {
println("Rendering a Secondary Button")
}
}
object ButtonFactory {
const val PRIMARY = "Primary"
const val SECONDARY = "Secondary"

fun createButton(type: String): Button {
return when (type) {
PRIMARY -> PrimaryButton()
SECONDARY -> SecondaryButton()
else -> throw IllegalArgumentException("Unknown Button type")
}
}
}
//Usage

fun main() {
val primaryButton = ButtonFactory.createButton(ButtonFactory.PRIMARY)
primaryButton.render() // Output: Rendering a Primary Button

val secondaryButton = ButtonFactory.createButton(ButtonFactory.SECONDARY)
secondaryButton.render() // Output: Rendering a Secondary Button
}

Why To use Factory Method Design Pattern

  1. Simplifies Object Creation: Instead of manually creating objects and dealing with their complex construction, the factory pattern provides a centralized place (the factory) where objects are created. This simplifies the code and makes it easier to manage.
  2. Reduces Code Duplication: You don’t have to write repetitive code to create objects.
  3. Improves Maintainability: If the creation process for objects changes, you only need to update the factory, not every place in the code where objects are created.
  4. Improves Maintainability: If the creation process for objects changes, you only need to update the factory, not every place in the code where objects are created.
  5. Enhances Code Organization: Keeps the object creation logic separate from the main logic, leading to cleaner and more organized code.

Abstract Factory

Instantiates various families of classes

Object Pool

Used when initialization cost of class is high

Prototype

Used when time taken to create object is large and costly. Objects are created with existing object itself.

Structural Design Patterns

Structural design patterns are a category of design patterns that focus on how objects and classes are composed to form larger structures. They help ensure that if one part of a system changes, the entire structure does not need to change as well.

These patterns are designed with regard to a class’s structure and composition. The main goal of most of these patterns is to increase the functionality of the class(es) involved, without changing much of its composition.

The main idea behind using structural patterns is to increase the functionality of the classes involved in the software without making many changes to its fundamental composition.

Types of structural patterns are:

  1. Adapter: Useful in matching the interfaces of various classes
    Example: RecyclerView.Adapter, Adapter
  2. Facade: The facade design pattern maintains a cover by providing an interface to the client, while hiding the complexities of the system.
    Example: Retrofit, Volley, Media Framework, DataBase query
  3. Bridge: Bridge design pattern is used to create a separation between the interface and its implementation.
  4. Decorator: This pattern helps in the addition of responsibility to objects dynamically.
  5. Proxy: This design pattern has objects representing other objects, like one student giving attendance for another student in college.
  6. Composite: Helpful in creating a proper tree like structure of simple and composite objects. This helps as you can represent the software design in hierarchies and each node in this tree structure can be designed to perform a specific task.
    Example: View & View Group
  7. Flyweight: This pattern helps in saving memory (essentially) by sharing the properties of objects.
  8. Private Class Data: Restricts the mutator or accessor access.

Adapter Design Pattern

The Adapter Design Pattern is a structural design pattern that allows objects with incompatible interfaces to work together. In Android, the Adapter pattern is commonly used to bridge the gap between data and UI components, making it possible for different types of data to be displayed in views like RecyclerView, ListView, or ViewPager.

  • Purpose: Allows incompatible interfaces to work together. It acts as a bridge between two objects.
  • It allows you to make systems that use incompatible formats work together without modifying their existing code.
  • You can easily add new types of data sources in the future without affecting the existing codebase.
  • In Code: In Android, the RecyclerView.Adapter is an example where the Adapter pattern is used to bind data to a RecyclerView.
//Adapter: Create a RecyclerView.Adapter class to bind the data to the ViewHolder.
class UserAdapter(private val userList: List<User>) : RecyclerView.Adapter<UserViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_user, parent, false)
return UserViewHolder(itemView)
}

override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val user = userList[position]
holder.userNameTextView.text = user.name
holder.userEmailTextView.text = user.email
}

override fun getItemCount(): Int {
return userList.size
}
}

//ViewHolder: Create a ViewHolder class that holds references to the views in each item.
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val userNameTextView: TextView = itemView.findViewById(R.id.userNameTextView)
val userEmailTextView: TextView = itemView.findViewById(R.id.userEmailTextView)
}


/*
How the Adapter Pattern Works Here
Incompatible Interfaces: The RecyclerView expects data to be in the form of ViewHolders, but your data is in the form of a list of User objects.
Adapter as the Bridge: The UserAdapter acts as the bridge between the User objects and the RecyclerView. It converts each User object into a format that the RecyclerView can understand and display.
Reusability: The RecyclerView.Adapter allows the RecyclerView to efficiently reuse views, improving performance by avoiding the creation of new views for every item.
*/

Facade Design Pattern

The Facade Design Pattern is a structural design pattern that provides a simplified interface to a complex subsystem, making it easier to interact with. It hides the complexities of the subsystem and provides a more user-friendly interface for the client code. This pattern is particularly useful when a system is complex or difficult to understand, as it abstracts away the details and provides a cleaner, more manageable API.
Example: Retrofit, Volley, Media Framework, DataBase query

Uses of the Facade Design Pattern

i. Simplifying Complex Systems:

  • Why?: Large systems often consist of multiple subsystems with complicated interactions. A facade provides a simpler, higher-level interface that reduces the learning curve for developers and makes the system easier to use.
  • In simpler terms, a facade acts as a wrapper around a set of APIs or functionalities, offering a simpler way for the client to interact with the underlying subsystems without needing to understand the complexities or details of each individual component.
  • Example: A facade might wrap multiple steps involved in connecting to a database, running a query, and processing results into a single method call.

ii. Decoupling Client Code from Subsystems:

  • Why?: By interacting with a facade instead of the underlying subsystems, client code becomes decoupled from the specific implementations of those subsystems. This makes it easier to change or replace the underlying subsystems without affecting the client code.
  • Example: In Android, if you want to switch from one networking library to another, having a facade can make the transition smoother.

iii. Improving Maintainability:

  • Why?: A facade centralizes interactions with the subsystems, making it easier to maintain and modify. Changes to the subsystem can be made behind the facade without requiring changes to the client code.
  • Example: If you need to change the way a complex set of operations is performed (like updating a UI based on data from multiple sources), you can do so within the facade without impacting other parts of your app.

Example: Retrofit: How Retrofit Acts as a Facade?

  • Simplifies Network Requests: Retrofit simplifies the process of making network requests and parsing responses by providing a clean and easy-to-use interface. Instead of manually handling HTTP requests, parsing JSON, or managing threads, you simply define an interface with annotations, and Retrofit handles the rest.
  • Hides Complexity: The complex tasks of creating and managing HTTP connections, converting data formats (like JSON to Java/Kotlin objects), and error handling are hidden behind Retrofit’s simple interface.
  • Unified Interface: Retrofit provides a unified interface for making network requests, regardless of the complexity of the underlying HTTP operations.
//Craete API interface 
interface ApiService {
@GET("user/profile")
fun getUserProfile(@Header("Authorization") token: String): Call<UserProfile>
}


//Create instance / object of Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://api.myexample.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()


//Geting the Retrofit instnace of
val apiService = retrofit.create(ApiService::class.java)

//Calling get user User from API interface using restrofit instace
val call = apiService.getUserProfile("Bearer token123")

//Enquing the api request
call.enqueue(object : Callback<UserProfile> {
override fun onResponse(call: Call<UserProfile>, response: Response<UserProfile>) {
// Handle successful response
}

override fun onFailure(call: Call<UserProfile>, t: Throwable) {
// Handle failure
}
})

Proxy Design Pattern

The Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. The proxy object acts as an intermediary, forwarding requests to the original object while potentially adding additional functionality, such as access control, logging, or lazy initialization.

Example in ContentProvider as a Proxy
In Android, the ContentProvider acts as a proxy to access data stored in a different process (often in a database). It allows an application to access data from another application in a controlled and secure manner.

Example in Image Loading with Virtual Proxy
Suppose you have an app that loads images from the internet. Loading an image is an expensive operation, so you want to use a proxy to load and display a placeholder image while the actual image is being fetched.

Decorator Design Pattern

The Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects, dynamically and transparently, without affecting the behavior of other objects from the same class. This pattern is useful when you want to enhance or modify the functionality of an object at runtime.

Example in Android: View Decorations
In Android, the Decorator pattern is commonly used in UI components. One of the most common examples is decorating a RecyclerView with ItemDecoration, which allows you to add custom drawing (e.g., dividers, margins, etc.) to the items in the list.

//RecycleView Items view decoration 
recyclerView.addItemDecoration(DividerItemDecoration(context))


//Items decoration logic
class DividerItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val divider: Drawable? = ContextCompat.getDrawable(context, R.drawable.divider)

override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
divider?.let {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight

for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + it.intrinsicHeight
it.setBounds(left, top, right, bottom)
it.draw(c)
}
}
}
}

Behavioral Design Pattern

Behavioral patterns are those design patterns that describe and identify the interactions between different objects. Making use of behavioral design patterns can reduce complicated flowcharts of the software design into simpler interconnections between various objects of classes.

These patterns are designed depending on how one class communicates with others.

Types of Behavioral Design Patterns:

  1. Observer: This design pattern acts as a notifier of change to multiple classes.
    Example: RxAndroid, RxJava, Broadcast Receiver, LiveData, EventBus
  2. State: The state design pattern is used when objects change their behavior based on their internal states.
  3. Chain of responsibility: An approach to passing a request between a chain of objects.
  4. Command: Data driven behavioral pattern, which encapculates all the information that is required for performing a “command” or action, or to trigger an event at a later time.
  5. Strategy: Strategy design pattern is also known as the policy pattern, that helps selecting algorithms at runtime.
  6. Visitor: This design pattern, separates an algorithm from the object structure on which it operates. It essentially results in the addition of new operations to the existing classes without any changes.
  7. Interpreter: Using this design pattern we can incorporate language elements in programs.
  8. Iterator: This pattern is utilized to get a method for getting to the components of a collection object in a sequential way with no requirement to know its fundamental representation.
  9. Mediator: Simplifies the communication between objects.
  10. Memento: Restores and captures objects internal states.

Observer Design Pattern

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically. This pattern is essential when you have multiple objects that need to be updated in response to a change in another object.

Key Concepts

  • Subject: The object that holds the state and notifies observers about state changes. It maintains a list of observers.
  • Observer: The objects that need to be notified when the subject changes state. Observers register themselves with the subject to receive updates.
  • Subscription: Observers subscribe to the subject, meaning they express interest in being notified of changes.
  • Notification: The process of the subject informing all registered observers about changes.

Example in Android: LiveData
In Android, one of the most common implementations of the Observer pattern is through LiveData and ViewModel in the Jetpack architecture components. LiveData is a lifecycle-aware observable data holder class that allows UI components to observe changes to data without worrying about lifecycle issues.

class MyViewModel : ViewModel() {
private val _textData = MutableLiveData<String>()
val textData: LiveData<String> get() = _textData

fun updateText(newText: String) {
_textData.value = newText
}
}



//In your Activity or Fragment

// Observer setup
viewModel.textData.observe(this, Observer { newText ->
// Update the UI when the data changes
textView.text = newText
})

// Simulate data change
viewModel.updateText("Hello, Observer Pattern!")

/*
ViewModel: Holds the LiveData object, which contains the data.
LiveData: The subject that notifies observers (UI components) when the data changes.
Observer: The Activity or Fragment that observes LiveData and updates the UI when notified of changes.
*/

--

--