Strategy pattern of Java design pattern

Posted by chocopi on Thu, 23 Dec 2021 14:56:30 +0100

Strategy mode

  • Definition: define a series of algorithms, encapsulate them one by one, and make them replaceable. This pattern allows the algorithm to vary independently of the customers using it.

  • Advantages: (1) policy pattern provides a way to manage related algorithm families. The hierarchical structure of policy class defines an algorithm or behavior family. Proper use of inheritance can move public code to the parent class, so as to avoid code duplication. (2) using policy pattern can avoid the use of multiple conditional (if else) statements. Multiple conditional statements are not easy to maintain. They mix the logic of which algorithm or behavior to adopt with the logic of algorithm or behavior. They are all listed in a multiple conditional statement, which is primitive and backward than the method of inheritance.

  • Disadvantages: (1) the client must know all policy classes and decide which policy class to use. This means that the client must understand the differences between these algorithms in order to select the appropriate algorithm class in time. In other words, the policy mode is only applicable when the client knows the algorithm or behavior. (2) Because the policy pattern encapsulates each specific policy implementation into a class, if there are many alternative policies, the number of objects will be considerable.

  • Blog: https://blog.csdn.net/hanchao5272/article/details/96480255 , https://www.cnblogs.com/java-my-life/archive/2012/05/10/2491891.html

  • Example: shopping cart payment strategy scenario: each item has a name and price. Multiple items can be added to the shopping cart. Shopping cart payment only supports Alipay and WeChat for the time being, but it may increase or decrease more payment later.

  • Class diagram:

  • code:

/**
 * Commodity category
 */
public class Goods {
    private String name;
    private Double price;

    public Goods(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public Double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

}
/**
 * Payment policy interface
 */
public interface PayStrategy {

    /**
     * payment
     *
     * @param cost
     */
    void pay(Double cost);
}
/**
 * Specific payment strategy - Alipay
 */
public class AliPayStrategy implements PayStrategy {
    @Override
    public void pay(Double cost) {
        System.out.println("Paid by Alipay. " + cost + " element");
    }
}
/**
 * Specific payment strategy - UnionPay
 */
public class UnionPayStrategy implements PayStrategy {
    @Override
    public void pay(Double cost) {
        System.out.println("Paid with UnionPay " + cost + "element");
    }
}
/**
 * Specific payment strategy - wechat
 */
public class WechatPayStrategy implements PayStrategy {
    @Override
    public void pay(Double cost) {
        System.out.println("Paid with wechat " + cost + " element");
    }
}
/**
 * @author wmy
 * @date 2021/8/11 17:16
 */

/**
 * Shopping Cart
 */
public class StrategyShoppingCart {
    /**
     * Product list
     */
    private List<Goods> goodsList;
    /**
     * Payment strategy
     */
    private PayStrategy payStrategy;

    public StrategyShoppingCart() {
        this.goodsList = new ArrayList<>();
    }

    /**
     * Add item
     *
     * @param goods
     */
    public void addGoods(Goods goods) {
        this.goodsList.add(goods);
    }

    /**
     * Calculate total price
     *
     * @return
     */
    public Double calcCost() {
        Double totalCost = 0.0;
        for (Goods goods : this.goodsList) {
            totalCost += goods.getPrice();
        }
        return totalCost;
    }

    /**
     * Select payment strategy
     *
     * @param payStrategy
     */
    public void setPayStrategy(PayStrategy payStrategy) {
        this.payStrategy = payStrategy;
    }

    /**
     * payment
     */
    public void pay() {
        this.payStrategy.pay(this.calcCost());
    }
}

/**
 * Test strategy mode
 */
public class TestStrategy {
    public static void main(String[] args) {
        //Alipay payment
        StrategyShoppingCart strategyShoppingCart1 = new StrategyShoppingCart();
        strategyShoppingCart1.addGoods(new Goods("A carton of milk", 34.55));
        strategyShoppingCart1.addGoods(new Goods("A bottle of Baijiu", 250.50));
        strategyShoppingCart1.setPayStrategy(new AliPayStrategy());
        strategyShoppingCart1.pay();

        //UnionPay payment
        StrategyShoppingCart strategyShoppingCart2 = new StrategyShoppingCart();
        strategyShoppingCart2.addGoods(new Goods("A carton of milk", 34.55));
        strategyShoppingCart2.addGoods(new Goods("A bottle of beer", 3.50));
        strategyShoppingCart2.setPayStrategy(new UnionPayStrategy());
        strategyShoppingCart2.pay();
    }
}

Topics: Java Design Pattern Algorithm