Design PatternsIntermediate
1Question 1 of 1
javaWhat are common Design Patterns in Java (Singleton, Builder, Strategy)?
Explanation & Concept
• Builder Pattern: Separates the construction of a complex object from its representation, avoiding constructor parameter explosion. • Strategy Pattern: Defines a family of algorithms, encapsulating each one and making them interchangeable at runtime.
Code Example
java
// Builder Pattern Implementation
public class ServerConfig {
private final String host;
private final int port;
private final boolean ssl;
private ServerConfig(Builder builder) {
this.host = builder.host;
this.port = builder.port;
this.ssl = builder.ssl;
}
public static class Builder {
private String host = "localhost";
private int port = 8080;
private boolean ssl = false;
public Builder host(String host) { this.host = host; return this; }
public Builder port(int port) { this.port = port; return this; }
public Builder ssl(boolean ssl) { this.ssl = ssl; return this; }
public ServerConfig build() { return new ServerConfig(this); }
}
}
// Fluent usage:
ServerConfig cfg = new ServerConfig.Builder().host("api.domain.com").port(443).ssl(true).build();How It Works & Key Takeaways
The Builder pattern provides readable, fluent object configuration without needing telescoping constructors with multiple ambiguous parameters.
Mock Test · 1 Questions · Optional
Ready for Functional Interfaces?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions