java中優(yōu)化大量if...else...方法總結(jié)
策略模式(Strategy Pattern)
將每個(gè)條件分支的實(shí)現(xiàn)作為一個(gè)獨(dú)立的策略類,然后使用一個(gè)上下文對(duì)象來(lái)選擇要執(zhí)行的策略。這種方法可以將大量的if else語(yǔ)句轉(zhuǎn)換為對(duì)象之間的交互,從而提高代碼的可維護(hù)性和可擴(kuò)展性。
示例:
首先,我們定義一個(gè)接口來(lái)實(shí)現(xiàn)所有策略的行為:
public interface PaymentStrategy {
void pay(double amount);
}接下來(lái),我們定義具體的策略類來(lái)實(shí)現(xiàn)不同的支付方式:
public class CreditCardPaymentStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardPaymentStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {
this.name = name;
this.cardNumber = cardNumber;
this.cvv = cvv;
this.dateOfExpiry = dateOfExpiry;
}
public void pay(double amount) {
System.out.println(amount + " paid with credit card");
}
}
public class PayPalPaymentStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PayPalPaymentStrategy(String emailId, String password) {
this.emailId = emailId;
this.password = password;
}
public void pay(double amount) {
System.out.println(amount + " paid using PayPal");
}
}
public class CashPaymentStrategy implements PaymentStrategy {
public void pay(double amount) {
System.out.println(amount + " paid in cash");
}
}現(xiàn)在,我們可以在客戶端代碼中創(chuàng)建不同的策略對(duì)象,并將它們傳遞給一個(gè)統(tǒng)一的支付類中,這個(gè)支付類會(huì)根據(jù)傳入的策略對(duì)象來(lái)調(diào)用相應(yīng)的支付方法:
public class ShoppingCart {
private List<Item> items;
public ShoppingCart() {
this.items = new ArrayList<>();
}
public void addItem(Item item) {
this.items.add(item);
}
public void removeItem(Item item) {
this.items.remove(item);
}
public double calculateTotal() {
double sum = 0;
for (Item item : items) {
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentStrategy) {
double amount = calculateTotal();
paymentStrategy.pay(amount);
}
}現(xiàn)在我們可以使用上述代碼來(lái)創(chuàng)建一個(gè)購(gòu)物車,向其中添加一些商品,然后使用不同的策略來(lái)支付:
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234", 10);
Item item2 = new Item("5678", 40);
cart.addItem(item1);
cart.addItem(item2);
// pay by credit card
cart.pay(new CreditCardPaymentStrategy("John Doe", "1234567890123456", "786", "12/22"));
// pay by PayPal
cart.pay(new PayPalPaymentStrategy("myemail@example.com", "mypassword"));
// pay in cash
cart.pay(new CashPaymentStrategy());
//--------------------------或者提前將不同的策略對(duì)象放入map當(dāng)中,如下
Map<String, PaymentStrategy> paymentStrategies = new HashMap<>();
paymentStrategies.put("creditcard", new CreditCardPaymentStrategy("John Doe", "1234567890123456", "786", "12/22"));
paymentStrategies.put("paypal", new PayPalPaymentStrategy("myemail@example.com", "mypassword"));
paymentStrategies.put("cash", new CashPaymentStrategy());
String paymentMethod = "creditcard"; // 用戶選擇的支付方式
PaymentStrategy paymentStrategy = paymentStrategies.get(paymentMethod);
cart.pay(paymentStrategy);
}
}工廠模式(Factory Pattern)
將每個(gè)條件分支的實(shí)現(xiàn)作為一個(gè)獨(dú)立的產(chǎn)品類,然后使用一個(gè)工廠類來(lái)創(chuàng)建具體的產(chǎn)品對(duì)象。這種方法可以將大量的if else語(yǔ)句轉(zhuǎn)換為對(duì)象的創(chuàng)建過(guò)程,從而提高代碼的可讀性和可維護(hù)性。
示例:
// 定義一個(gè)接口
public interface StringProcessor {
public void processString(String str);
}
// 實(shí)現(xiàn)接口的具體類
public class LowercaseStringProcessor implements StringProcessor {
public void processString(String str) {
System.out.println(str.toLowerCase());
}
}
public class UppercaseStringProcessor implements StringProcessor {
public void processString(String str) {
System.out.println(str.toUpperCase());
}
}
public class ReverseStringProcessor implements StringProcessor {
public void processString(String str) {
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse().toString());
}
}
// 工廠類
public class StringProcessorFactory {
public static StringProcessor createStringProcessor(String type) {
if (type.equals("lowercase")) {
return new LowercaseStringProcessor();
} else if (type.equals("uppercase")) {
return new UppercaseStringProcessor();
} else if (type.equals("reverse")) {
return new ReverseStringProcessor();
}
throw new IllegalArgumentException("Invalid type: " + type);
}
}
// 測(cè)試代碼
public class Main {
public static void main(String[] args) {
StringProcessor sp1 = StringProcessorFactory.createStringProcessor("lowercase");
sp1.processString("Hello World");
StringProcessor sp2 = StringProcessorFactory.createStringProcessor("uppercase");
sp2.processString("Hello World");
StringProcessor sp3 = StringProcessorFactory.createStringProcessor("reverse");
sp3.processString("Hello World");
}
}看起來(lái)還是有if...else,但這樣的代碼更加簡(jiǎn)潔易懂,后期也便于維護(hù)....
映射表(Map)
使用一個(gè)映射表來(lái)將條件分支的實(shí)現(xiàn)映射到對(duì)應(yīng)的函數(shù)或方法上。這種方法可以減少代碼中的if else語(yǔ)句,并且可以動(dòng)態(tài)地更新映射表,從而提高代碼的靈活性和可維護(hù)性。
示例:
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class MappingTableExample {
private Map<String, Function<Integer, Integer>> functionMap;
public MappingTableExample() {
functionMap = new HashMap<>();
functionMap.put("add", x -> x + 1);
functionMap.put("sub", x -> x - 1);
functionMap.put("mul", x -> x * 2);
functionMap.put("div", x -> x / 2);
}
public int calculate(String operation, int input) {
if (functionMap.containsKey(operation)) {
return functionMap.get(operation).apply(input);
} else {
throw new IllegalArgumentException("Invalid operation: " + operation);
}
}
public static void main(String[] args) {
MappingTableExample example = new MappingTableExample();
System.out.println(example.calculate("add", 10));
System.out.println(example.calculate("sub", 10));
System.out.println(example.calculate("mul", 10));
System.out.println(example.calculate("div", 10));
System.out.println(example.calculate("mod", 10)); // 拋出異常
}
}數(shù)據(jù)驅(qū)動(dòng)設(shè)計(jì)(Data-Driven Design)
將條件分支的實(shí)現(xiàn)和輸入數(shù)據(jù)一起存儲(chǔ)在一個(gè)數(shù)據(jù)結(jié)構(gòu)中,然后使用一個(gè)通用的函數(shù)或方法來(lái)處理這個(gè)數(shù)據(jù)結(jié)構(gòu)。這種方法可以將大量的if else語(yǔ)句轉(zhuǎn)換為數(shù)據(jù)結(jié)構(gòu)的處理過(guò)程,從而提高代碼的可擴(kuò)展性和可維護(hù)性。
示例:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class DataDrivenDesignExample {
private List<Function<Integer, Integer>> functionList;
public DataDrivenDesignExample() {
functionList = new ArrayList<>();
functionList.add(x -> x + 1);
functionList.add(x -> x - 1);
functionList.add(x -> x * 2);
functionList.add(x -> x / 2);
}
public int calculate(int operationIndex, int input) {
if (operationIndex < 0 || operationIndex >= functionList.size()) {
throw new IllegalArgumentException("Invalid operation index: " + operationIndex);
}
return functionList.get(operationIndex).apply(input);
}
public static void main(String[] args) {
DataDrivenDesignExample example = new DataDrivenDesignExample();
System.out.println(example.calculate(0, 10));
System.out.println(example.calculate(1, 10));
System.out.println(example.calculate(2, 10));
System.out.println(example.calculate(3, 10));
System.out.println(example.calculate(4, 10)); // 拋出異常
}
}總結(jié)
到此這篇關(guān)于java中優(yōu)化大量if...else...的文章就介紹到這了,更多相關(guān)java優(yōu)化大量if...else...內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
RestTemplate響應(yīng)中如何獲取輸入流InputStream
這篇文章主要介紹了RestTemplate響應(yīng)中如何獲取輸入流InputStream問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
JSP 開(kāi)發(fā)之 releaseSession的實(shí)例詳解
這篇文章主要介紹了JSP 開(kāi)發(fā)之 releaseSession的實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-07-07
Java+mysql實(shí)現(xiàn)學(xué)籍管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java+mysql實(shí)現(xiàn)學(xué)籍管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07
基于Java SWFTools實(shí)現(xiàn)把pdf轉(zhuǎn)成swf
這篇文章主要介紹了基于Java SWFTools實(shí)現(xiàn)把pdf轉(zhuǎn)成swf,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
java使用google身份驗(yàn)證器實(shí)現(xiàn)動(dòng)態(tài)口令驗(yàn)證的示例
本篇文章主要介紹了java使用google身份驗(yàn)證器實(shí)現(xiàn)動(dòng)態(tài)口令驗(yàn)證的示例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08
使用Java應(yīng)用程序添加或刪除 PDF 中的附件
當(dāng)我們?cè)谥谱鱌DF文件或者PPT演示文稿的時(shí)候,為了讓自己的文件更全面詳細(xì),就會(huì)在文件中添加附件,那么如何添加或刪除PDF中的附件呢,今天通過(guò)本文給大家詳細(xì)講解,需要的朋友參考下吧2023-01-01
springboot使用com.github.binarywang包實(shí)現(xiàn)微信網(wǎng)頁(yè)上的支付和退款
最近做項(xiàng)目需要實(shí)現(xiàn)在pc端需要實(shí)現(xiàn)微信的支付,本文主要介紹了springboot使用com.github.binarywang包實(shí)現(xiàn)微信網(wǎng)頁(yè)上的支付和退款,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05
java將數(shù)據(jù)寫入內(nèi)存,磁盤的方法
下面小編就為大家分享一篇java將數(shù)據(jù)寫入內(nèi)存,磁盤的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01

