圖片
“厄運(yùn)之塔”或“波動(dòng)拳代碼”
讓我們逐一深入探討這些策略,并給出示例。
策略模式定義了一系列算法,封裝了每一個(gè)算法,并使它們可以互相替換。當(dāng)你有多種方式來執(zhí)行某個(gè)特定任務(wù)時(shí),這種模式就很有用。
首先,定義一個(gè)PaymentStrategy接口:
public interface PaymentStrategy { void pay(double amount);}
接下來,實(shí)現(xiàn)不同的支付策略:
@Componentpublic class CreditCardPayment implements PaymentStrategy { @Override public void pay(double amount) { // 信用卡支付處理邏輯 System.out.println("Paid " + amount + " using Credit Card."); }}@Componentpublic class PaypalPayment implements PaymentStrategy { @Override public void pay(double amount) { // PayPal支付處理邏輯 System.out.println("Paid " + amount + " using PayPal."); }}
創(chuàng)建一個(gè)使用該策略的PaymentService:
@Servicepublic class PaymentService { private final Map<String, PaymentStrategy> paymentStrategies = new HashMap<>(); public PaymentService(List<PaymentStrategy> strategies) { for (PaymentStrategy strategy : strategies) { paymentStrategies.put(strategy.getClass().getSimpleName(), strategy); } } public void processPayment(String strategyName, double amount) { PaymentStrategy strategy = paymentStrategies.get(strategyName); if (strategy != null) { strategy.pay(amount); } else { throw new IllegalArgumentException("No such payment strategy: " + strategyName); } }}
枚舉可用于表示一組預(yù)定義的常量及其相關(guān)行為。
定義一個(gè)OrderStatus枚舉并賦予不同的行為:
public enum OrderStatus { NEW { @Override public void handle() { System.out.println("Processing new order."); } }, SHIPPED { @Override public void handle() { System.out.println("Order shipped."); } }, DELIVERED { @Override public void handle() { System.out.println("Order delivered."); } }; public abstract void handle();}
在服務(wù)中使用這個(gè)枚舉:
@Servicepublic class OrderService { public void processOrder(OrderStatus status) { status.handle(); }}
多態(tài)允許對(duì)象被視為其父類的實(shí)例,而不是其實(shí)際類。這使你能夠通過父類的引用調(diào)用派生類的重寫方法。
定義一個(gè)Notification接口及其實(shí)現(xiàn):
public interface Notification { void send(String message);}public class EmailNotification implements Notification { @Override public void send(String message) { // 發(fā)送電子郵件的邏輯 System.out.println("Sending email: " + message); }}public class SmsNotification implements Notification { @Override public void send(String message) { // 發(fā)送短信的邏輯 System.out.println("Sending SMS: " + message); }}
創(chuàng)建一個(gè)使用多態(tài)的服務(wù):
@Servicepublic class NotificationService { private final List<Notification> notifications; public NotificationService(List<Notification> notifications) { this.notifications = notifications; } public void notifyAll(String message) { for (Notification notification : notifications) { notification.send(message); } }}
Lambda表達(dá)式可以簡化你的代碼,特別是在處理小型、單方法接口時(shí)。
定義一個(gè)使用Lambda表達(dá)式的折扣服務(wù):
import java.util.HashMap;import java.util.Map;import java.util.function.Function;public class DiscountService { private Map<String, Function<Double, Double>> discountStrategies = new HashMap<>(); public DiscountService() { discountStrategies.put("SUMMER_SALE", price -> price * 0.9); discountStrategies.put("WINTER_SALE", price -> price * 0.8); } public double applyDiscount(String discountCode, double price) { return discountStrategies.getOrDefault(discountCode, Function.identity()).apply(price); }}
命令模式將請(qǐng)求封裝為一個(gè)對(duì)象,從而允許你使用隊(duì)列、請(qǐng)求和操作對(duì)客戶端進(jìn)行參數(shù)化。
定義命令接口及其具體實(shí)現(xiàn):
public interface Command { void execute();}public class OpenFileCommand implements Command { private FileSystemReceiver fileSystem; public OpenFileCommand(FileSystemReceiver fs) { this.fileSystem = fs; } @Override public void execute() { this.fileSystem.openFile(); }}public class CloseFileCommand implements Command { private FileSystemReceiver fileSystem; public CloseFileCommand(FileSystemReceiver fs) { this.fileSystem = fs; } @Override public void execute() { this.fileSystem.closeFile(); }}
定義FileSystemReceiver和Invoker:
public interface FileSystemReceiver { void openFile(); void closeFile();}public class UnixFileSystemReceiver implements FileSystemReceiver { @Override public void openFile() { System.out.println("Opening file in Unix OS"); } @Override public void closeFile() { System.out.println("Closing file in Unix OS"); }}public class FileInvoker { private Command command; public FileInvoker(Command cmd) { this.command = cmd; } public void execute() { this.command.execute(); }}
Guard子句提供了一種提前處理?xiàng)l件的方式,通過盡早處理無效條件,使你的代碼更加易讀,并減少嵌套結(jié)構(gòu)。
在這里不嵌套if-else語句來驗(yàn)證用戶輸入,而是使用Guard子句來提前處理無效情況:
public class UserService { public void registerUser(User user) { if (user == null) { throw new IllegalArgumentException("User cannot be null"); } if (user.getName() == null || user.getName().isEmpty()) { throw new IllegalArgumentException("User name cannot be empty"); } if (user.getEmail() == null || user.getEmail().isEmpty()) { throw new IllegalArgumentException("User email cannot be empty"); } // Proceed with registration System.out.println("Registering user: " + user.getName()); }}
這種方法可確保及早處理無效條件,并使主要邏輯保持簡潔易懂。
通過應(yīng)用這些策略,你可以大大減少在Java Spring Boot項(xiàng)目中使用if-else語句。這不僅使你的代碼更可讀,也提高了其可維護(hù)性和可擴(kuò)展性。采用這些模式和實(shí)踐來編寫更簡潔、更高效的代碼吧。
本文鏈接:http://www.tebozhan.com/showinfo-26-94726-0.html重構(gòu)Java Spring Boot代碼,消除If-Else語句
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com