Design Patterns in Java: JavaBean and Singleton Design Pattern Explained with Examples
📘 Design Pattern in Java
A Design Pattern is a reusable solution to commonly occurring problems in software design and application development.
Design patterns help developers write clean, maintainable, scalable, and efficient code.
They do not provide code directly, but they provide best practices and standard approaches to solve design issues.
Design patterns help developers write clean, maintainable, scalable, and efficient code.
They do not provide code directly, but they provide best practices and standard approaches to solve design issues.
🔷 JavaBean Design Pattern
A JavaBean Design Pattern is used to create simple, reusable, and encapsulated Java classes mainly for data transfer within an application.
✅ Rules of JavaBean Class
A JavaBean class must follow these rules:
- The class must be declared as public
- It may implement the Serializable marker interface
- All instance variables must be private
- It must contain public getter (accessor) and setter (mutator) methods
- It must have a public or protected constructor
- It should not contain business logic (recommended)
🎯 Purpose of JavaBean Design Pattern
- Used for data transportation inside an application
- The object of a JavaBean class is called a Data Transfer Object (DTO)
- Achieves Encapsulation
- Supports Data Hiding using private variables
🌍 Real-Life Example
Think of a JavaBean like a filled application form:
- Fields are private (secured)
- Values are accessed using getter/setter
- Used to transfer data from one department to another
🔷 Singleton Design Pattern
A Singleton Design Pattern ensures that only one object of a class is created and that object is shared across the entire application.
✅ Rules of Singleton Class
A Singleton class must follow these rules:
- The class must have a private constructor
- It must contain a private static instance variable
- The object must be returned using a public static method
- It can contain any number of instance variables and instance methods
- Only one instance of the class exists in the application
🎯 Purpose of Singleton Design Pattern
- Used when a single object is shared by multiple classes
- Controls object creation
- Saves memory
- Ensures consistent behavior across the application
🌍 Real-Life Example
Think of a printer in an office:
- Only one printer exists
- Multiple users access the same printer
- Singleton ensures only one printer object
🛠️ Real-World Uses of Singleton
- Configuration classes
- Logger classes
- Database connection managers
- Cache managers
Comments
Post a Comment