美文网首页
设计模式第7篇:策略模式

设计模式第7篇:策略模式

作者: 大厂offer | 来源:发表于2017-12-13 12:21 被阅读26次
    • 策略设计模式是一种行为设计模式,一个最典型的例子就是 Collections.sort() 方法,其返回的结果取决于不同的Comparator实现;
    • 举一个生活中的例子,当我们结算购物车的时候,我们可以选择信用卡支付或者Paypal支付,两种支付方式就是不同的策略体现。
    • 首先我们可以创建一个策略模式的接口,然后将金额作为参数传递进去。

    PaymentStrategy.java

    package com.journaldev.design.strategy;
    
    public interface PaymentStrategy {
    
        public void pay(int amount);
    }
    

    现在我们再创建一个包含具体算法的PaymentStrategy具体实现类:CreditCardStrategy ,CreditCardStrategy.java

    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");
        }
    
    }
    

    PaypalStrategy.java

    package com.journaldev.design.strategy;
    
    public class PaypalStrategy implements PaymentStrategy {
    
        private String emailId;
        private String password;
        
        public PaypalStrategy(String email, String pwd){
            this.emailId=email;
            this.password=pwd;
        }
        
        @Override
        public void pay(int amount) {
            System.out.println(amount + " paid using Paypal.");
        }
    
    }
    

    Item.java

    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;
        }
        
    }
    

    好,现在策略已经准备好了!我们可以实现购物车和支付方法。

    ShoppingCart.java

    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);
        }
    }
    

    注意在ShoppingCart类的pay()方法中,需要将具体的支付方法作为参数传递进去;请看接下来的测试示例:
    ShoppingCartTest.java

    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("myemail@example.com", "mypwd"));
            
            //pay by credit card
            cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
        }
    
    }
    

    输出:

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

    Strategy Design Pattern Important Points

    • 避免将特定的策略运用于特定的任务
    • trategy Pattern is very similar toState Pattern. One of the difference is that Context contains state as instance variable and there can be multiple tasks whose implementation can be dependent on the state whereas in strategy pattern strategy is passed as argument to the method and context object doesn’t have any variable to store it.(这一点不太好翻译,请参考知乎经典解释:https://www.zhihu.com/question/23693088/answer/25364323

    相关文章

      网友评论

          本文标题:设计模式第7篇:策略模式

          本文链接:https://www.haomeiwen.com/subject/egraixtx.html