- EFFECTIVE
- Constructors
- Composition
- Interfaces Default
- Import Static
- Enums
- Lambdas
- JUNIT
- About Junit
- Test Case
- Suite Test
- Annotations
- Exceptions
- LAMBDAS
- Expressions
- Functional Interfaces
- Streams
- Common Operations
- Default Methods
- Static Methods
- Single Responsibility
- THREADS
- Create Thread
- Sleep
- Lock
- Scheduler
- DESIGN PATTERNS
-
Singleton
- Observer
- Dependency Injection
- Strategy
- Mediator
SINGLE INSTANCE
Singleton pattern restricts the instantiation of a class to a single instance. A private constructor hides the class for outside.
class LearningApp {
public static void main(String[] args) {
MyClass A = MyClass.getInstance();
MyClass B = MyClass.getInstance();
MyClass C = new MyClass();
// Error: The constructor MyClass() is not visible
}
}
class MyClass {
private static final MyClass INSTANCE = new MyClass();
private MyClass() {} // private constructor
public static MyClass getInstance() {
return INSTANCE;
}
}
The static keyword is used for unique initialization.
A static class is not automatically a Singleton class.
class LearningApp {
public static void main(String[] args) {
Obj o1 = new Obj();
System.out.println( o1.getInstances() );// count = 1
Obj o2 = new Obj();
System.out.println( o2.getInstances() );// count = 1
}
private static class Obj {
private int count = 0; // it should be declared static
private Obj() {
count++; // without static it is always 1
}
public int getInstances() {
return count;
}
}
}
Last update: 452 days ago