Strategy Pattern
Implement each conditional branch as an independent strategy class, and then use a context object to select the strategy to be executed. This method can convert a large number of if else statements into interactions between objects, thereby improving the maintainability and scalability of the code.
Example:
First, we define an interface to implement the behavior of all strategies:
public interface PaymentStrategy { void pay(double amount); }
Next, we define specific strategy classes to implement different Payment method:
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"); } }
Now, we can create different policy objects in the client code and pass them to a unified payment class. This payment class will call the corresponding policy object based on the incoming policy object. Payment method:
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); } }
Now we can use the above code to create a shopping cart, add some items to it, and then use different strategies to pay:
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); } }
Factory Pattern
Treat the implementation of each conditional branch as an independent product class, and then use a factory class to create specific product objects. This method can convert a large number of if else statements into the object creation process, thus improving the readability and maintainability of the code.
Example:
// 定义一个接口 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"); } }
It seems that there is still if...else, but this code is more concise and easy to understand, and it is easier to maintain later....
Mapping table (Map)
Use a mapping table to map the implementation of conditional branches to the corresponding functions or methods. This method can reduce if else statements in the code and can dynamically update the mapping table, thereby improving the flexibility and maintainability of the code.
Example:
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)); // 抛出异常 } }
Data-Driven Design
Store the implementation of conditional branches and the input data together in a data structure , and then use a common function or method to process this data structure. This method can convert a large number of if else statements into data structure processing, thereby improving the scalability and maintainability of the code.
Example:
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)); // 抛出异常 } }
The above is the detailed content of How to optimize a large number of if...else... in java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor