Junior — Middle
Can you name the main ways to implement popular design patterns?
sobes.tech AI
Answer from AI
Main ways to implement popular design patterns in Java:
- Singleton: a class with a private constructor and a static method to get the single instance.
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- Factory Method: defines an interface for creating an object, allowing subclasses to alter the type of objects that will be created.
public interface Product {}
public class ConcreteProduct implements Product {}
public abstract class Creator {
public abstract Product factoryMethod();
}
public class ConcreteCreator extends Creator {
public Product factoryMethod() {
return new ConcreteProduct();
}
}
- Observer: an object (observer) subscribes to events of another object (subject) and receives notifications about changes.
public interface Observer {
void update();
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer o) { observers.add(o); }
public void notifyObservers() {
for (Observer o : observers) {
o.update();
}
}
}
- Decorator: dynamically adds new responsibilities to objects by wrapping them.
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
public void operation() { System.out.println("Main operation"); }
}
public class Decorator implements Component {
protected Component component;
public Decorator(Component c) { this.component = c; }
public void operation() {
component.operation();
}
}
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component c) { super(c); }
public void operation() {
super.operation();
System.out.println("Additional behavior");
}
}
These are just a few examples, but in Java, most patterns are implemented through interfaces, abstract classes, and composition.