Java에서 많은 if...else...를 최적화하는 방법
Strategy Pattern
각 조건부 분기를 독립적인 전략 클래스로 구현한 다음 컨텍스트 개체를 사용하여 실행할 전략을 선택합니다. 이 방법은 많은 수의 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); } }
Factory Pattern
각 조건부 분기를 독립적인 제품 클래스로 구현한 다음 팩토리 클래스를 사용하여 특정 제품 개체를 만듭니다. 이 방법을 사용하면 수많은 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가 있는 것 같지만 이 코드가 더 간결하고 이해하기 쉽고 나중에 유지 관리도 더 쉽습니다....
매핑 테이블(Map)
매핑 테이블을 사용하여 조건부 분기 구현을 해당 함수 또는 메서드에 매핑합니다. 이 방법은 코드의 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)); // 抛出异常 } }
Data-Driven Design
조건 분기의 구현과 입력 데이터를 데이터 구조에 함께 저장한 다음 공통 함수나 방법을 사용하여 이 데이터 구조를 처리합니다. 이 방법은 많은 수의 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 난수 생성기 안내. 여기서는 예제를 통해 Java의 함수와 예제를 통해 두 가지 다른 생성기에 대해 설명합니다.

Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

Java의 TimeStamp to Date 안내. 여기서는 소개와 예제와 함께 Java에서 타임스탬프를 날짜로 변환하는 방법에 대해서도 설명합니다.

캡슐은 3 차원 기하학적 그림이며, 양쪽 끝에 실린더와 반구로 구성됩니다. 캡슐의 부피는 실린더의 부피와 양쪽 끝에 반구의 부피를 첨가하여 계산할 수 있습니다. 이 튜토리얼은 다른 방법을 사용하여 Java에서 주어진 캡슐의 부피를 계산하는 방법에 대해 논의합니다. 캡슐 볼륨 공식 캡슐 볼륨에 대한 공식은 다음과 같습니다. 캡슐 부피 = 원통형 볼륨 2 반구 볼륨 안에, R : 반구의 반경. H : 실린더의 높이 (반구 제외). 예 1 입력하다 반경 = 5 단위 높이 = 10 단위 산출 볼륨 = 1570.8 입방 단위 설명하다 공식을 사용하여 볼륨 계산 : 부피 = π × r2 × h (4
