用策略模式实现购物车,策略模式实现购物车,public class
分享于 点击 29184 次 点评:239
用策略模式实现购物车,策略模式实现购物车,public class
public class ShoppingCart { private final List<Item> items; public ShoppingCart() { items = new ArrayList<Item>(); } public void addItem(Item item) { items.add(item); } public double calcTotalCost() { double total = 0.0; for (Item item : items) { total += item.getPrice(); } return total; } public boolean pay(PaymentMethod method) { double totalCost = calcTotalCost(); return method.pay(totalCost); }}
我们可以看到上面的pay方法的参数是一个PaymentMethod实例,这就意味着我们可以根据需要切换不同的支付策略。
public interface PaymentMethod { public boolean pay(double amount);}
这样你就可以定义任意支付方式的PaymentMethod了。
public class Visa implements PaymentMethod { private final String name; private final String cardNumber; private final Date expires; public Visa(String name, String cardNumber, Date expires) { super(); this.name = name; this.cardNumber = cardNumber; this.expires = expires; } @Override public boolean pay(double amount) { // Open Comms to Visa // Verify connection // Paybill using these details return true; // if payment goes through }}
public class MasterCard implements PaymentMethod { private final String name; private final String cardNumber; private final Date expires; public MasterCard(String name, String cardNumber, Date expires) { super(); this.name = name; this.cardNumber = cardNumber; this.expires = expires; } @Override public boolean pay(double amount) { // Open Comms to Mastercard // Verify connection // Paybill using these details return true; // if payment goes through }}
用户点评