Below are examples of some common design patterns in Java along with brief explanations of each.
1. Singleton Pattern
- Ensures that a class has only one instance and provides a global point of access to it.public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. Factory Method Pattern
- Defines an interface for creating an object, but leaves the choice of its type to the subclasses, creating the instance of the class.interface Product {
void create();
}
class ConcreteProductA implements Product {
public void create() {
System.out.println("Product A created");
}
}
class ConcreteProductB implements Product {
public void create() {
System.out.println("Product B created");
}
}
interface Creator {
Product factoryMethod();
}
class ConcreteCreatorA implements Creator {
public Product factoryMethod() {
return new ConcreteProductA();
}
}
class ConcreteCreatorB implements Creator {
public Product factoryMethod() {
return new ConcreteProductB();
}
}
3. 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.import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
4. Decorator Pattern
- Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() {
System.out.println("Basic operation");
}
}
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("Additional operation");
}
}
These are just a few examples, and there are many more design patterns with various use cases. Implementing and understanding these patterns can lead to more maintainable and scalable software designs.
Nenhum comentário:
Postar um comentário