Singleton Pattern
Singleton Pattern
Singleton pattern is one of the simplest design patterns in Java. This type of
design pattern comes under creational pattern as this pattern provides one
of the best ways to create an object.
Implementation
We're going to create a SingleObject class. SingleObject class have its
constructor as private and have a static instance of itself.
SingleObject.java
Step 2
SingletonPatternDemo.java
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
Step 3
Hello World!
Factory Pattern (Creational Pattern)
Factory pattern is one of the most used design patterns in Java. This type of
design pattern comes under creational pattern as this pattern provides one
of the best ways to create an object.
Implementation
Create an interface.
Shape.java
Step 2
Rectangle.java
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
Step 3
ShapeFactory.java
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
Step 4
FactoryPatternDemo.java
Step 5