Design Patterns
Design Patterns
Design patterns are reusable solutions to the most commonly occurring software problems. They can speed up the development process by providing a proven way of resolving frequent issues.
Design patterns can be divided into three sections:
· Creational Design Patterns deliver solutions for creating classes, objects (Singleton, Factory, Builder, etc.)
· Structural Design Patterns are about the arrangement of classes and objects (e.g. Composite, Facade, Adapter)
· Behavioral Design Patterns give us ways to communicate between objects and classes (Command, Observer, Strategy, etc.)
Example :
Builder Pattern
Builder pattern simplifies object creation in a very clean and readable way. It’s very helpful when we have some model classes with many parameters. We can make some of them optional or required, and we don’t force the user to use a specific order.
Ex:
Let’s assume we have some model class, instead of creating objects of this class using constructors, we want to create them using Builder pattern.
static class Builder {
private String firstName;
private String lastName;
private int age;
public Builder setFirstName(final String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(final String lastName) {
this.lastName = lastName;
return this;
}
public Builder setAge(final int age) {
this.age = age;
return this;
}
public User create() {
return new User(this);
}
}
creating object using builder:
new User.Builder()
.setFirstName(“Leonardo”)
.setLastName(“da Vinci”)
.setAge(67)
.create();
Android Design Patterns: The Singleton Pattern
The Singleton Pattern is a software design pattern that guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class.
In a typical Android app, there are many objects for which we only need one global instance, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClient
, HttpLoggingInterceptor
, Retrofit
, Gson
, SharedPreferences
, the repository class, etc. If we were to instantiate more than one of these types of objects, we'd run into problems like incorrect app behavior, resource overuse
Example: Creating a Single Instance of Retrofit
import
retrofit2.Retrofit;
import
retrofit2.converter.gson.GsonConverterFactory;
public
class
RetrofitClient {
private
static
Retrofit retrofit = null;
public
static
Retrofit getClient(String baseUrl) {
if
(retrofit==null) {
retrofit = new
Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return
retrofit;
}
}
So anytime client A calls RetrofitClient.getClient()
, it creates the instance if it has not been created already, and then when client B calls this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one.