user124
user124

Reputation: 493

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("[email protected]", "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?

Upvotes: 1

Views: 779

Answers (1)

dung ta van
dung ta van

Reputation: 1026

1. I want to ask what is use of strategy pattern here?

The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)

2. We can directly call pay() method from there?

I don't know exactly you mean

3. Why do we need interface , all which does is call a method?

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:

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("[email protected]", "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();
    }

}

Upvotes: 1

Related Questions