重点等级::star::star::star:
定义一个算法组,封装每一个算法,并使其可互换。策略让算法独立于使用它的客户端而独立地变化。
在有多种算法相似的情况下,避免过多if else语句的尴尬。
以一个支付场景为例,支付是可以使用 Paypal、信用卡等等,可以使用不同的策略来进行代码设计。
//支付接口
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");
}
}
//Paypal 支付
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 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"));
//50 paid using Paypal.
//50 paid with credit/debit card
}
}
public enum ChannelRuleEnum {
/**
* 头条
*/
TOUTIAO("TOUTIAO",new TouTiaoChannelRule()),
/**
* 腾讯
*/
TENCENT("TENCENT",new TencentChannelRule()),
;
public String name;
public GeneralChannelRule channel;
ChannelRuleEnum(String name, GeneralChannelRule channel) {
this.name = name;
this.channel = channel;
}
//匹配
public static ChannelRuleEnum match(String name){
ChannelRuleEnum[] values = ChannelRuleEnum.values();
for (ChannelRuleEnum value : values) {
if(value.name.equals(name)){
return value;
}
}
return null;
}
public String getName() {
return name;
}
public GeneralChannelRule getChannel() {
return channel;
}
}
public static void main(String[] args) {
String sign = "TOUTIAO";
ChannelRuleEnum channelRule = ChannelRuleEnum.match(sign);
GeneralChannelRule rule = channelRule.channel;
rule.xxx();
}