Senior
Tell us about the design patterns you used in the project
sobes.tech AI
Answer from AI
In Java projects, I often use the following design patterns:
- Singleton — for creating a single instance of a class, for example, for a configuration manager or connection pool.
- Factory Method — for creating objects without tightly coupling to specific classes, which facilitates extensibility.
- Builder — for convenient and safe construction of complex objects with many parameters.
- Decorator — for dynamically adding functionality to objects without changing their code.
- Observer — for implementing event-driven models, for example, when subscribing to state changes.
- Strategy — for selecting an algorithm for behavior at runtime.
Example of using Builder to create an object:
public class User {
private String name;
private int age;
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
public static class Builder {
private String name;
private int age;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public User build() {
return new User(this);
}
}
}
// Usage:
User user = new User.Builder()
.setName("Ivan")
.setAge(30)
.build();