Effective Java: Enums And Annotations
Jether Rodrigues
Senior Software Engineer | Java | Kotlin | Spring | Web3 | Solidity | Smart Contracts | Blockchain | Chainlink Advocate
Understanding Enums and Annotations in Java
Enums and annotations are powerful features in Java that can significantly improve the readability, maintainability, and robustness of your code. Chapter 6 of "Effective Java" by Joshua Bloch delves into these features, providing best practices and practical advice on how to use them effectively. Here’s a detailed summary of the key points from this chapter:
Example: Using Enums with the Strategy Design Pattern
Below is an example of using enums to implement the Strategy Design Pattern for executing different types of payment methods.
import java.math.BigDecimal;
// Define the Strategy interface with @FunctionalInterface annotation
@FunctionalInterface
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
// Implement different payment strategies
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(BigDecimal amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
public class PayPalPayment implements PaymentStrategy {
@Override
public void pay(BigDecimal amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// Define an enum to represent different payment methods
public enum PaymentMethod {
CREDIT_CARD(new CreditCardPayment()),
PAYPAL(new PayPalPayment());
private final PaymentStrategy strategy;
PaymentMethod(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void pay(BigDecimal amount) {
strategy.pay(amount);
}
}
// Strategy execution
public class Main {
public static void main(String[] args) {
final PaymentMethod method = PaymentMethod.CREDIT_CARD;
final BigDecimal amount = new BigDecimal("100.00");
switch (method) {
case CREDIT_CARD:
method.pay(amount);
break;
case PAYPAL:
method.pay(amount);
break;
default:
throw new IllegalArgumentException("Unknown payment method: " + method);
}
}
}
In this example, the PaymentStrategy interface is annotated with @FunctionalInterface, and the pay method uses BigDecimal for precise monetary values. The Main class uses a switch case to handle different PaymentMethod values and execute the corresponding payment strategy. This approach ensures type safety, precision, and flexibility in handling different payment methods.
#Java #EffectiveJava #Enums #Annotations
Fullstack Software Engineer | Java | Javascript | Go | GoLang | Angular | Reactjs | AWS
3 个月Thanks for sharing