목차
Strategy Pattern
Factory Pattern
매핑 테이블(Map)
Data-Driven Design
Java java지도 시간 Java에서 많은 if...else...를 최적화하는 방법

Java에서 많은 if...else...를 최적화하는 방법

Apr 15, 2023 am 10:01 AM
java

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

자바의 제곱근 자바의 제곱근 Aug 30, 2024 pm 04:26 PM

자바의 제곱근

자바의 완전수 자바의 완전수 Aug 30, 2024 pm 04:28 PM

자바의 완전수

Java의 난수 생성기 Java의 난수 생성기 Aug 30, 2024 pm 04:27 PM

Java의 난수 생성기

자바의 암스트롱 번호 자바의 암스트롱 번호 Aug 30, 2024 pm 04:26 PM

자바의 암스트롱 번호

자바의 웨카 자바의 웨카 Aug 30, 2024 pm 04:28 PM

자바의 웨카

Java의 스미스 번호 Java의 스미스 번호 Aug 30, 2024 pm 04:28 PM

Java의 스미스 번호

Java Spring 인터뷰 질문 Java Spring 인터뷰 질문 Aug 30, 2024 pm 04:29 PM

Java Spring 인터뷰 질문

Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Feb 07, 2025 pm 12:09 PM

Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까?

See all articles