admin管理员组

文章数量:1566678

定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们可以相互替换,让算法独立于使用它的客户而独立变化。

这个模式涉及到三个角色:

环境(Context)角色:持有一个Strategy的引用。

抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

具体策略(ConcreteStrategy)角色:包装了相关的具体算法或行为。

策略模式的典型代码如下:

①策略接口:

/**
 * 策略 接口
 */
public interface Strategy {

    /**
     * 策略方法
     */
    void strategyInterface();
}

②具体策略:

public class ConcreateStrategyA implements Strategy {

    @Override
    public void strategyInterface() {
        //do something
    }
}

public class ConcreateStrategyB implements Strategy {
    @Override
    public void strategyInterface() {
        //do something
    }
}

③环境(Context)

public class Content {
    private Strategy strategy;

    public Content(Strategy strategy){
        this.strategy=strategy;
    }
    /**
     * 策略方法
     */
    public void contextInterface(){

        strategy.strategyInterface();
    }
}

具体使用示例:

针对不同会员等级,商品折扣不相同,普通打9.5折,会员打9折。

策略:

public interface Strategy {

    /**
     * 策略方法
     */
    void strategyPrice(Double price);
}

具体策略:

public class UserStrategy implements Strategy {

    @Override
    public Double strategyPrice(Double price) {
        price=price*0.95;
        return price;
    }
}

public class VipUserStrategy implements Strategy {

    @Override
    public Double strategyPrice(Double price) {
        price=price*0.90;
        return price;
    }
}

环境:

public class Content {
    private Strategy strategy;

    public Content(String  userType){
        if(userType=="user"){
            this.strategy= new UserStrategy();
        }
        if(userType=="vip"){
            this.strategy= new VipUserStrategy();
        }
        
    }
    /**
     * 策略方法
     */
    public void contextInterface(Double price){

        strategy.strategyPrice(price);
    }
}

具体客户端:

new Content("vip").contextInterface(19.88);

new Content("user").contextInterface(19.88);

 策略设计模式与Spring整合

@Component
public class Content {

    @Autowired 
    Map<String, Strategy> strategyMap = new ConcurrentHashMap<>(); 
   
    
    /**
     * 策略方法
     */
    public void getStrategy(String userType){

        strategyMap.get(userType).strategyPrice();
    }
}

本文标签: 模式策略Strategy