Skip to main content

Strategy Design Pattern – Java 8

java design pattern

1) Introduction

We are going to look at how to implement the Strategy Design Pattern in Java. Then, explaining how to leverage Java 8 features to reduce code verbosity.

The Strategy design pattern is a behavioral design pattern. This can use for change the behavior of algorithm/logic at runtime.

2) Implementation

For an example, We need to implement payment logic. A customer can choose credit card or cash as a payment method. But, there are two different logic to calculate final payment.

Create an interface, PaymentStrategy.java

Then, time to implement the payment logic.

CashPaymentStrategy.java

CreditCardPaymentStrategy.java

The implementation is done. Now, we are going to test it.


output

3) Leveraging Java 8

In Java 8 has a feature to define static methods in the interface. So that, we are going to use that to reduce code verbosity. First of all, get rid of the CashPaymentStrategy.java and CreditCardPaymentStrategy.java.

to test it.


 

 


Related Post

5764total visits,4visits today

RSS
Follow by Email
Facebook
Facebook
Google+
http://mydevgeek.com/strategy-design-pattern-java-8
Twitter