Development

Java의 전략 디자인 패턴 :이 기사는 알고리즘 제품군을 정의하고 각각을 캡슐화하고 상호 교환 할 수있는 전략 설계 패턴을 다룰 수 있습니다.전략을 사용하면 알고리즘을 사용하는 클라이언..

sonpro 2023. 3. 11. 12:10
반응형

Strategy design pattern

Strategy Design Pattern in Java

In software development, design patterns are reusable solutions to common problems that arise during software design. One of the most popular design patterns is the Strategy design pattern, which defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

In this article, we will explore the Strategy design pattern in Java and how it can be used to improve the flexibility and maintainability of your code.

Understanding the Strategy Design Pattern

The Strategy design pattern is a behavioral pattern that allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern enables you to select an algorithm at runtime, based on the context or the client's requirements.

In the Strategy pattern, you have a set of algorithms that perform a specific task. Each algorithm is encapsulated in a separate class, and all of them implement a common interface. The client code interacts with the algorithms through this interface, which makes the algorithms interchangeable.

The following diagram illustrates the basic structure of the Strategy design pattern:

Strategy Design Pattern

The Context class contains a reference to the Strategy interface, which is implemented by the ConcreteStrategy classes. The client code interacts with the Context class, which in turn delegates the task to the appropriate ConcreteStrategy object.

Benefits of the Strategy Design Pattern

The Strategy design pattern offers several benefits, including:

  • Flexibility: The Strategy pattern allows you to change the behavior of an object at runtime, without affecting the client code. You can add new algorithms or modify existing ones without changing the client code.
  • Maintainability: The Strategy pattern promotes code reuse and separation of concerns. Each algorithm is encapsulated in a separate class, which makes it easier to maintain and test the code.
  • Simplicity: The Strategy pattern simplifies the client code by hiding the complexity of the algorithms behind a common interface. The client code only needs to interact with the Context class, which delegates the task to the appropriate algorithm.

Example of the Strategy Design Pattern in Java

Let's consider an example of how the Strategy design pattern can be used in Java. Suppose we have a PaymentProcessor class that processes payments for an online store. The PaymentProcessor class needs to support different payment methods, such as credit card, PayPal, and Bitcoin.

We can use the Strategy design pattern to encapsulate each payment method in a separate class and make them interchangeable. Here's how the code would look like:

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

public class CreditCardStrategy implements PaymentStrategy {
    private String name;
    private String cardNumber;
    private String cvv;
    private String dateOfExpiry;

    public CreditCardStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {
        this.name = name;
        this.cardNumber = cardNumber;
        this.cvv = cvv;
        this.dateOfExpiry = dateOfExpiry;
    }

    @Override
    public void pay(double amount) {
        System.out.println(amount + " paid with credit card");
    }
}

public class PayPalStrategy implements PaymentStrategy {
    private String email;
    private String password;

    public PayPalStrategy(String email, String password) {
        this.email = email;
        this.password = password;
    }

    @Override
    public void pay(double amount) {
        System.out.println(amount + " paid with PayPal");
    }
}

public class BitcoinStrategy implements PaymentStrategy {
    private String bitcoinAddress;

    public BitcoinStrategy(String bitcoinAddress) {
        this.bitcoinAddress = bitcoinAddress;
    }

    @Override
    public void pay(double amount) {
        System.out.println(amount + " paid with Bitcoin");
    }
}

public class PaymentProcessor {
    private PaymentStrategy paymentStrategy;

    public PaymentProcessor(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void processPayment(double amount) {
        paymentStrategy.pay(amount);
    }
}

In this example, we have a PaymentStrategy interface that defines the common interface for all payment methods. We also have three ConcreteStrategy classes: CreditCardStrategy, PayPalStrategy, and BitcoinStrategy, which implement the PaymentStrategy interface.

The PaymentProcessor class represents the Context class, which contains a reference to the PaymentStrategy interface. The processPayment() method delegates the payment task to the appropriate ConcreteStrategy object.

We can use the PaymentProcessor class to process payments using different payment methods, as shown in the following code:

PaymentProcessor processor = new PaymentProcessor(new CreditCardStrategy("John Doe", "1234567890123456", "123", "12/24"));
processor.processPayment(100.0);

processor = new PaymentProcessor(new PayPalStrategy("john.doe@example.com", "password"));
processor.processPayment(50.0);

processor = new PaymentProcessor(new BitcoinStrategy("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"));
processor.processPayment(200.0);

In this example, we create a PaymentProcessor object for each payment method and call the processPayment() method with the amount to be paid. The PaymentProcessor class delegates the payment task to the appropriate ConcreteStrategy object, which performs the payment using the selected payment method.

Conclusion

The Strategy design pattern is a powerful tool that can help you improve the flexibility and maintainability of your code. By encapsulating algorithms in separate classes and making them interchangeable, you can change the behavior of an object at runtime, without affecting the client code. This pattern promotes code reuse and separation of concerns, which makes it easier to maintain and test your code.

In this article, we explored the Strategy design pattern in Java and how it can be used to implement different payment methods in an online store. We hope this article has helped you understand the benefits of the Strategy pattern and how to use it in your own projects.

반응형