行为模式之策略模式

2019-09-18  本文已影响0人  后来丶_a24d

总纲

策略模式

/**
 *  策略模式能避免出现大量的 if...else
 *  在需要从三个数据库读取三种不同处罚记录的时候选择了策略模式,保持controller层代码纯净
 *  拓展时只需要加类方便
 */
public interface NumStrategies {
    void doSomething();
}

public class FirstStrategies implements NumStrategies {
    @Override
    public void doSomething() {
        System.out.println(" I am  firstStrategy");
    }
}

public class SecondStrategy implements NumStrategies {
    @Override
    public void doSomething() {
        System.out.println(" I am  secondStrategy");
    }
}

public class Context {
    private  NumStrategies numStrategies;

    Context(NumStrategies numStrategies){
        this.numStrategies = numStrategies;
    }

    public static Context builderStrategies(Integer strategyNum){
        if(strategyNum == 1){
            return new Context(new FirstStrategies());
        }
        if(strategyNum == 2){
            return new Context(new SecondStrategy());
        }
        return new Context(new FirstStrategies());
    }
    public void doSomething(){
        numStrategies.doSomething();
    }
}
上一篇下一篇

猜你喜欢

热点阅读