Javaで多数のif...else...を最適化する方法
戦略パターン
各条件分岐を独立した戦略クラスとして実装し、コンテキスト オブジェクトを使用して実行する戦略を選択します。この方法では、多数の if else ステートメントをオブジェクト間の相互作用に変換できるため、コードの保守性とスケーラビリティが向上します。
例:
まず、すべての戦略の動作を実装するインターフェイスを定義します:
public interface PaymentStrategy { void pay(double amount); }
次に、さまざまな支払い方法を実装するための特定の戦略クラスを定義します。 :
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"); } }
これで、クライアント コードでさまざまなポリシー オブジェクトを作成し、それらを統合支払いクラスに渡すことができます。この支払いクラスは、受信したポリシー オブジェクトに基づいて、対応するポリシー オブジェクトを呼び出します。支払い方法:
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); } }
これで、上記のコードを使用してショッピング カートを作成し、そこにいくつかのアイテムを追加し、さまざまな戦略を使用して支払いを行うことができます:
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当中,如下 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); } }
ファクトリー パターン
各条件分岐の実装を独立した製品クラスとして扱い、ファクトリ クラスを使用して特定の製品オブジェクトを作成します。この方法では、多数の if else ステートメントをオブジェクト作成プロセスに変換できるため、コードの可読性と保守性が向上します。
例:
// 定义一个接口 public interface StringProcessor { public void processString(String str); } // 实现接口的具体类 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 があるようですが、このコードの方が簡潔で理解しやすく、後のメンテナンスも容易です。 ..
マッピング テーブル (マップ)
#マッピング テーブルを使用して、条件付き分岐の実装を対応する関数またはメソッドにマップします。この方法では、コード内の if else ステートメントを削減し、マッピング テーブルを動的に更新できるため、コードの柔軟性と保守性が向上します。例:
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)); // 抛出异常 } }
条件分岐の実装と入力データを一緒にデータ構造に格納し、次を使用します。このデータ構造を処理するための共通の関数またはメソッド。この方法では、多数の if else ステートメントをデータ構造処理に変換できるため、コードの拡張性と保守性が向上します。例:
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)); // 抛出异常 } }
以上がJavaで多数のif...else...を最適化する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

Java での日付までのタイムスタンプに関するガイド。ここでは、Java でタイムスタンプを日付に変換する方法とその概要について、例とともに説明します。

カプセルは3次元の幾何学的図形で、両端にシリンダーと半球で構成されています。カプセルの体積は、シリンダーの体積と両端に半球の体積を追加することで計算できます。このチュートリアルでは、さまざまな方法を使用して、Javaの特定のカプセルの体積を計算する方法について説明します。 カプセルボリュームフォーミュラ カプセルボリュームの式は次のとおりです。 カプセル体積=円筒形の体積2つの半球体積 で、 R:半球の半径。 H:シリンダーの高さ(半球を除く)。 例1 入力 RADIUS = 5ユニット 高さ= 10単位 出力 ボリューム= 1570.8立方ユニット 説明する 式を使用してボリュームを計算します。 ボリューム=π×R2×H(4
