最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java中優(yōu)化大量if...else...方法總結(jié)

 更新時間:2023年03月18日 10:26:23   作者:提筆忘字的帝國  
在我們平時的開發(fā)過程中,經(jīng)常可能會出現(xiàn)大量If else的場景,代碼顯的很臃腫,非常不優(yōu)雅,下面這篇文章主要給大家介紹了關(guān)于java中優(yōu)化大量if...else...方法的相關(guān)資料,需要的朋友可以參考下

策略模式(Strategy Pattern)

將每個條件分支的實(shí)現(xiàn)作為一個獨(dú)立的策略類,然后使用一個上下文對象來選擇要執(zhí)行的策略。這種方法可以將大量的if else語句轉(zhuǎn)換為對象之間的交互,從而提高代碼的可維護(hù)性和可擴(kuò)展性。

示例:

 首先,我們定義一個接口來實(shí)現(xiàn)所有策略的行為:

public interface PaymentStrategy {
    void pay(double amount);
}

接下來,我們定義具體的策略類來實(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)建不同的策略對象,并將它們傳遞給一個統(tǒng)一的支付類中,這個支付類會根據(jù)傳入的策略對象來調(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)在我們可以使用上述代碼來創(chuàng)建一個購物車,向其中添加一些商品,然后使用不同的策略來支付: 

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());
 
        //--------------------------或者提前將不同的策略對象放入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)

將每個條件分支的實(shí)現(xiàn)作為一個獨(dú)立的產(chǎn)品類,然后使用一個工廠類來創(chuàng)建具體的產(chǎn)品對象。這種方法可以將大量的if else語句轉(zhuǎn)換為對象的創(chuàng)建過程,從而提高代碼的可讀性和可維護(hù)性。

示例: 

// 定義一個接口
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);
    }
}
 
// 測試代碼
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");
    }
}

 看起來還是有if...else,但這樣的代碼更加簡潔易懂,后期也便于維護(hù)....

映射表(Map)

使用一個映射表來將條件分支的實(shí)現(xiàn)映射到對應(yīng)的函數(shù)或方法上。這種方法可以減少代碼中的if else語句,并且可以動態(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ū)動設(shè)計(jì)(Data-Driven Design) 

將條件分支的實(shí)現(xiàn)和輸入數(shù)據(jù)一起存儲在一個數(shù)據(jù)結(jié)構(gòu)中,然后使用一個通用的函數(shù)或方法來處理這個數(shù)據(jù)結(jié)構(gòu)。這種方法可以將大量的if else語句轉(zhuǎn)換為數(shù)據(jù)結(jié)構(gòu)的處理過程,從而提高代碼的可擴(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談基于SpringBoot實(shí)現(xiàn)一個簡單的權(quán)限控制注解

    淺談基于SpringBoot實(shí)現(xiàn)一個簡單的權(quán)限控制注解

    這篇文章主要介紹了基于SpringBoot實(shí)現(xiàn)一個簡單的權(quán)限控制注解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Spring Boot2.x集成JPA快速開發(fā)的示例代碼

    Spring Boot2.x集成JPA快速開發(fā)的示例代碼

    這篇文章主要介紹了Spring Boot2.x集成JPA快速開發(fā),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • SpringBoot中使用MyBatis-Plus詳細(xì)步驟

    SpringBoot中使用MyBatis-Plus詳細(xì)步驟

    MyBatis-Plus是MyBatis的增強(qiáng)工具,簡化了MyBatis的使用,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2025-01-01
  • Java虛擬機(jī)精選面試題20道

    Java虛擬機(jī)精選面試題20道

    現(xiàn)在面試Java開發(fā)時,基本都會問到Java虛擬機(jī)的知識,根據(jù)職位不同問的內(nèi)容深淺又有所區(qū)別。本文整理了10道面試中常問的Java虛擬機(jī)面試題,希望對正在面試的同學(xué)有所幫助
    2021-06-06
  • SpringBoot結(jié)合WebSocket實(shí)現(xiàn)聊天功能

    SpringBoot結(jié)合WebSocket實(shí)現(xiàn)聊天功能

    本文介紹了如何使用SpringBoot和WebSocket實(shí)現(xiàn)一個簡單的聊天功能,包括導(dǎo)入依賴、配置類、創(chuàng)建消息實(shí)體、指定ServerEndpoint、創(chuàng)建客戶端等步驟,通過具體示例,演示了如何發(fā)送個人消息和群發(fā)消息,實(shí)現(xiàn)了基本的聊天功能,適合需要在項(xiàng)目中實(shí)現(xiàn)實(shí)時通訊功能的開發(fā)者參考
    2024-11-11
  • Java中synchronized?的4個優(yōu)化技巧

    Java中synchronized?的4個優(yōu)化技巧

    本文主要介紹了Java中synchronized的4個優(yōu)化技巧,synchronized在JDK?1.5?時性能是比較低的,然而在后續(xù)的版本中經(jīng)過各種優(yōu)化迭代,它的性能也得到了前所未有的提升,下文更多相關(guān)資料需要的小伙伴可以參考一下
    2022-05-05
  • 如何用Spring發(fā)送電子郵件

    如何用Spring發(fā)送電子郵件

    這篇文章主要介紹了如何用Spring發(fā)送電子郵件,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2021-02-02
  • spring boot加載freemarker模板路徑的方法

    spring boot加載freemarker模板路徑的方法

    這篇文章主要介紹了spring boot加載freemarker模板路徑的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • springboot打成jar后無法讀取根路徑和文件的解決

    springboot打成jar后無法讀取根路徑和文件的解決

    這篇文章主要介紹了springboot打成jar后無法讀取根路徑和文件的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Minio環(huán)境部署過程及如何配置HTTPS域名

    Minio環(huán)境部署過程及如何配置HTTPS域名

    MinIO?是一個對象存儲系統(tǒng),數(shù)據(jù)需要存儲在宿主機(jī)上,容器的重啟不影響數(shù)據(jù),因此我們需要為?MinIO?創(chuàng)建一個掛載目錄,用于持久化存儲數(shù)據(jù),本文詳細(xì)介紹了如何部署MinIO,并通過配置反向代理和HTTPS來提升其安全性,感興趣的朋友一起看看吧
    2025-03-03

最新評論

大方县| 新建县| 新安县| 睢宁县| 儋州市| 康定县| 红安县| 临安市| 湖南省| 渝北区| 无为县| 漾濞| 浦县| 阜宁县| 永寿县| 彭州市| 罗源县| 甘南县| 镇巴县| 海城市| 广安市| 永吉县| 富平县| 历史| 奉新县| 金昌市| 东辽县| 濮阳市| 湾仔区| 乌海市| 藁城市| 抚远县| 连江县| 尚志市| 海林市| 大名县| 西昌市| 文昌市| 商都县| SHOW| 永善县|