简体   繁体   English

策略设计模式示例?

[英]Strategy design pattern Example?

Following is stretagy design pattern example take from here .以下是从这里获取的策略设计模式示例。 First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.首先,我们将为我们的策略创建接口,在我们的例子中,支付作为参数传递的金额。

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

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



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


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

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



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

I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface, all which does is call a method?我想问这里策略模式有什么用?一旦我们在main中创建了策略。我们现在可以访问策略class。我们可以直接从那里调用pay()方法?为什么我们需要接口,所有这些就是调用方法?

1. I want to ask what is use of strategy pattern here? 1.我想问这里策略模式有什么用?

The answer is the user who has the ShoppingCart ( ShoppingCart cart = new ShoppingCart(); )答案是拥有 ShoppingCart 的用户( ShoppingCart cart = new ShoppingCart();

2. We can directly call pay() method from there? 2.我们可以直接从那里调用pay()方法吗?

I don't know exactly you mean我不知道你的意思

3. Why do we need interface, all which does is call a method? 3. 为什么我们需要接口,它所做的只是调用一个方法?

We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:我们需要PaymentStrategy接口,因为我们需要使用多态来实现多种支付方式(paypal 或信用卡),让我们稍微更改一下源代码,您可以更清楚地看到:

 public class ShoppingCart { // other functions public void pay(PaymentStrategy paymentMethod, int amount){ paymentMethod.pay(amount); } public void payWithStrategy() { int amount = calculateTotal(); if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal pay(new PaypalStrategy("myemail@example.com", "mypwd"), amount); } else { // you really like credit card so when the money lower than the card limit, you always choose it pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount); } } } 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); cart.payWithStrategy(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM