Strategy mode in Java, complete a simple shopping cart, two payment strategy example tutorials

The strategy mode is a behavior mode . There are multiple algorithm strategies to choose from for a specific project, and the client decides to use a specific algorithm strategy according to different needs when it is running.

Strategy mode is also called policy mode. The implementation process is to first define different algorithm strategies, and then the client uses the algorithm strategy as one of its parameters. The best example of using this pattern is the Collection.sort() method, which uses a Comparator object as a parameter. According to different implementations of the Comparator interface, the objects will be sorted by different methods.

The example in this article is to complete a simple shopping cart, two payment strategies are available, one is a credit card, the other is Paypal.

First, create a strategy interface. In this example, the payment amount is used as a parameter.

package com.journaldev.design.strategy;

public interface PaymentStrategy {

    public void pay(int amount);
}

Now implement entity classes that use credit card and Paypal algorithm strategies.

package com.journaldev.design.strategy;

public class CreditCardStrategy implements PaymentStrategy {

    private String name;
    private String cardNumber;
    private String cvv;
    private String dateOfExpiry;

    public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
        this.name=nm;
        this.cardNumber=ccNum;
        this.cvv=cvv;
        this.dateOfExpiry=expiryDate;
    }
    @Override
    public void pay(int amount) {
        System.out.println(amount +" paid with credit/debit card");
    }

}

At this point, the algorithm strategy is ready, and now it is necessary to implement a shopping cart and a payment method that can use the payment strategy.

package com.journaldev.design.strategy;

public class Item {

    private String upcCode;
    private int price;

    public Item(String upc, int cost){
        this.upcCode=upc;
        this.price=cost;
    }

    public String getUpcCode() {
        return upcCode;
    }

    public int getPrice() {
        return price;
    }

}
package com.journaldev.design.strategy;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {

    //List of items
    List<Item> items;

    public ShoppingCart(){
        this.items=new ArrayList<Item>();
    }

    public void addItem(Item item){
        this.items.add(item);
    }

    public void removeItem(Item item){
        this.items.remove(item);
    }

    public int calculateTotal(){
        int sum = 0;
        for(Item item : items){
            sum += item.getPrice();
        }
        return sum;
    }

    public void pay(PaymentStrategy paymentMethod){
        int amount = calculateTotal();
        paymentMethod.pay(amount);
    }
}

Note that the payment method of the shopping cart accepts the payment strategy as a parameter, but does not save any instance variables inside it.

A simple test program.

package com.journaldev.design.strategy;

public class ShoppingCartTest {

    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 paypal
        cart.pay(new PaypalStrategy("[email protected]", "mypwd"));

        //pay by credit card
        cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
    }

}

The output is as follows:

50 paid using Paypal.
50 paid with credit/debit card

Important points:

  • The entity variables of the strategy can be constructed here, but this should be avoided as much as possible. Because it is necessary to ensure that a specific algorithm strategy can be corresponded to a specific task, it is similar to using the comparator as a parameter in the Collection.sort() and Array.sort() methods.

  • The strategy mode is similar to the state mode. The difference between the two is that the Context (environment object) in the state pattern contains instance variables of the state, and different tasks depend on the same state. On the contrary, in the strategy mode, the strategy is passed into the method as a parameter, and the context (environment object) does not need and cannot store any variables.

  • When a set of algorithms corresponds to a task, and the program can flexibly choose one of the algorithms at runtime, the strategy mode is a good choice.

This is all the Java strategy pattern, I hope you like it.

At last

Reply to the data by private message to receive a summary of Java interview questions from a major manufacturer + Alibaba Taishan manual + a learning guide for knowledge points + a summary of Java core knowledge points in a 300-page pdf document!

The content of these materials are all the knowledge points that the interviewer must ask during the interview. The chapter includes many knowledge points, including basic knowledge, Java collections, JVM, multi-threaded concurrency, spring principles, microservices, Netty and RPC, Kafka , Diary, design pattern, Java algorithm, database, Zookeeper, distributed cache, data structure, etc.

file

Guess you like

Origin blog.csdn.net/weixin_46577306/article/details/108013574