Skip to main content

Posts

Showing posts with the label Design Pattern

Design Patterns : Builder Pattern

Points To Remember It is a Creational Design Pattern It must be used when you have multiple overloaded constructors or setters Its main purpose it to hide from the user, how the object is to be created . It is advised to make your constructors private when you are using Builder Design Pattern. What is Builder Design Pattern It is a creational design pattern. So it is only responsible for how an object must be created. There may be scenarios where there is a class with many instance variables that may be needed to create an object of the class. For this you might have to create many overloaded constructors. For Example we have a class NutritionFacts that has following instance variables private int servingSize; private int servings; private int calories; private int fat; private int sodium; private int carbohydrate; Then to create the object of the class we can have constructors as follows NutritionFacts cocaCola = new NutritionFacts( 240 , 8 , ...

How to make a Class Singleton

Points To Remember To make a class Singleton the class must satisfy the following points No class should be able to make the object of this class. Only one object of this class must me there that is used by all the other classes. The class must have a private constructor so that no class should be able to make object of this class. Class should make a final object of the class itself and return it whenever asked for. Class should have a static method that returns the object of this class. Demo : Create a Singleton Class Class : Singleton.java public class Singleton{ private String name = "Singleton Object"; private static final Singleton object = new Singleton(); private Singleton(){ } public static Singleton getObject(){ return object; } public String getName(){ return name; } } Class : SingletonTest.java class SingletonTest{ public static void main(String args[]){ Singleton obj = Singleton.getObject(); System.out.println(obj.getName()); } } T...