设计模式一之 策略模式

策略模式= 环境类+抽象策略类+具体策略类
环境基础框架:spring boot
优点:
去除代码的耦合性,将之前的if…else…替换,将算法封装到某个类中
遵序开闭原则

示例代码

环境类

@Service
public class SimpleContext {

/**map中的String是将具体策略类的名称映射进来**/
    @Autowired
    private final Map strategyMap = new ConcurrentHashMap<>();

    public String getStategy(String id) {
    //通过map.get()已经确定了到底使用哪个具体策略类,但是在debug的时候,没办法看到,是因为此时的类型还是interface
        return strategyMap.get(id).getVpcList(id);
    }
}

抽象策略类

public interface Strategy {
    String getVpcList(String id);
}

具体策略类 A

@Component("A")
public class ResourceA implements Strategy {

    @Override
    public String getVpcList(String id) {
        System.out.println("A,getVpcList ===========" + id);
        return id;
    }
}

具体策略类B

@Component("B")
public class ResourceB implements Strategy {

    @Override
    public String getVpcList(String id) {
        System.out.println("B,getVpcList ===========" + id);
        return id;
    }
}

备注:
以上的代码示例,自我感觉是不是最优解。看过一个博主的代码,是将if…else…的内容替换成具体策略类的自定义注解,这样就不用map.get()了,通过注解的类型自动去寻找具体的实现

你可能感兴趣的:(设计模式)