Design Patterns

  1. Singleton Pattern.
  2. Immutable Object Pattern.
  3. Builder Pattern.
  4. Factory Pattern.

Singleton Pattern

Available balance: 25000.0
Available balance: 24750.0
Available balance: 24750.0
Available balance: 19750.0

Immutable Objects Pattern

String str = "apple";
System.out.println(str.toUpperCase()); // APPLE
System.out.println(str); // apple
// only way to change is to reassing with new object
str = str.toUpperCase();
  1. Use a constructor to set all properties of the object.
  2. Mark all of the instance variables as private and final.
  3. Don’t define any setters methods, but provide getters(so we can work with this object).
  4. Don’t allow referenced mutable objects to be accessed directly.
  5. Prevent methods from being overridden by making a class final or making all methods final.
[broccoli, squash, tomatoes]
[broccoli, squash, tomatoes]
  1. We are using a public constructor to set all properties.
  2. All our instance variables are private and final.
  3. We don’t have setters so we cannot modify properties. Only getters are provided to read the properties of an object.
  4. This one is important and easy to miss. If the object property is a mutable object then we have to return and set copies, otherwise, the client code can get direct access to the property and change it.
  5. Our class is final so it cannot have child classes hence the methods cannot be overridden.

Builder Pattern

[broccoli, squash, tomatoes]
Chicago Pizza
  1. We can easily add a new property to the Pizza object without changing the places where the Pizza objects were created with PizzaBuilder.
  2. We can create a Pizza object with only the required for us properties without maintaining multiple overloaded constructors.

Factory Pattern



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store