Top Java Design Patterns: Understanding the Concepts
Unveiling the Power of Java Design Patterns Through Practical Code Samples and Essential Definition.
public class ConfigurationManager {
private static ConfigurationManager instance;
private ConfigurationManager() {}public static ConfigurationManager getInstance() {
if(instance == null) {
instance = new ConfigurationManager();
}
return instance;
}
// Other configuration methods...
}
2. Factory Pattern:
Creates objects without exposing the instantiation logic to the client. Useful when you want to create different objects based on certain conditions. For example, a shape factory that creates different shapes:
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
// Similarly, define classes for other shapes like Rectangle, Triangle, etc.
public class ShapeFactory {
public Shape getShape(String shapeType) {
if(shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
}
// Add conditions for other shapes...
return null;
}
}
3. Observer Pattern:
Establishes a one-to-many dependency between objects. When one object changes state, all its dependents are notified and updated automatically. For example, a simple implementation for a weather station:
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(int temperature);
}
class WeatherStation {
private int temperature;
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void setTemperature(int temperature) {
this.temperature = temperature;
notifyObservers();
}
private void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature);
}
}
}
4. Strategy Pattern:
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Useful when you want to switch between similar algorithms. For example, a simple payment strategy implementation:
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardStrategy implements PaymentStrategy {
private String cardNumber;
private String cvv;
public CreditCardStrategy(String cardNumber, String cvv) {
this.cardNumber = cardNumber;
this.cvv = cvv;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid with credit/debit card");
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void pay(int amount) {
paymentStrategy.pay(amount);
}
}
5. Builder Pattern:
Top Java Design Patterns: Understanding the ConceptsSeparates the construction of a complex object from its representation. Useful when you want to create different representations of the same object. For example, a simple implementation for building a house:
class House {
private String floorType;
private int numberOfRooms;public House(String floorType, int numberOfRooms) {
this.floorType = floorType;
this.numberOfRooms = numberOfRooms;
}
// Getters and setters...
}
class HouseBuilder {
private String floorType;
private int numberOfRooms;
public HouseBuilder setFloorType(String floorType) {
this.floorType = floorType;
return this;
}
public HouseBuilder setNumberOfRooms(int numberOfRooms) {
this.numberOfRooms = numberOfRooms;
return this;
}
public House build() {
return new House(floorType, numberOfRooms);
}
}
// Usage:
House house = new HouseBuilder()
.setFloorType("Wooden")
.setNumberOfRooms(3)
.build();
Short Definitions of Design Patterns
here is a concise one-line explanation for each of the design patterns:
1. Singleton Pattern: Ensures a class has only one instance and provides a global point of access to it.
领英推荐
2. Factory Pattern: Creates objects without exposing the instantiation logic to the client and refers to the newly created object through a common interface.
3. Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
4. Builder Pattern: Separates the construction of a complex object from its representation, allowing the same construction process to create various representations.
5. Prototype Pattern: Creates new objects by copying an existing object, known as the prototype, through cloning.
6. Adapter Pattern: Allows the interface of an existing class to be used as another interface, making it compatible with what the client expects.
7. Bridge Pattern: Decouples an abstraction from its implementation so that the two can vary independently.
8. Composite Pattern: Composes objects into tree structures to represent part-whole hierarchies, allowing clients to treat individual objects and compositions of objects uniformly.
9. Decorator Pattern: Attaches additional responsibilities to an object dynamically, providing a flexible alternative to subclassing for extending functionality.
10. Facade Pattern: Provides a unified interface to a set of interfaces in a subsystem, simplifying the usage for clients.
11. Flyweight Pattern: Minimizes memory usage and improves performance by sharing as much data as possible with related objects.
12. Proxy Pattern: Provides a surrogate or placeholder for another object to control access to it.
13. Chain of Responsibility Pattern: Avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.
14. Command Pattern: Encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations.
15. Interpreter Pattern: Defines a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
16. Iterator Pattern: Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
17. Mediator Pattern: Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.
18. Memento Pattern: Captures and externalizes an object’s internal state so the object can be restored to this state later.
19. Observer Pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
20. State Pattern: Allows an object to alter its behavior when its internal state changes, thus appearing to change its class.
21. Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable, allowing the algorithm to vary independently from clients that use it.
22. Template Method Pattern: Defines the skeleton of an algorithm in a method, deferring some steps to subclasses, allowing them to redefine certain steps of the algorithm without changing its structure.
23. Visitor Pattern: This represents an operation to be performed on the elements of an object structure, allowing you to define a new operation without changing the classes of the elements on which it operates.
Head of Technology | Project management, HighPerformance, Design & Architecture, Leadership
1 年Good work Swapnil Take