一个策略模式Demo

主要解决一个什么问题

比如有个方法

public void sayHello(String type){
    if (type.equals("xiaoji")) {
        System.out.println("小鸡叫");
    }else if (type.equals("yazi")) {
        System.out.println("鸭子叫");
    }
}

这个代码有什么问题?如果后面要再加一个猪叫,是不是又要加一个if,这样不利于扩展

策略模式

一个接口,策略模式一般定义2个方法,一个用于批评类型,一个是具体的实现方法

public interface AnimalService {

    void sayHello();

    String getType();
}

小鸡实现类

@Service
public class XiaojiServiceImpl implements AnimalService {
    @Override
    public void sayHello() {
        System.out.println("小鸡叫");
    }

    @Override
    public String getType() {
        return "xiaoji";
    }
}

鸭子实现类

@Service
public class YaziServiceImpl implements AnimalService {
    @Override
    public void sayHello() {
        System.out.println("鸭子叫");
    }

    @Override
    public String getType() {
        return "yazi";
    }
}

策略方法类

@Component
public class AnimalStrategyServiceFactory implements ApplicationContextAware {

    private Map<String, AnimalService> map = new ConcurrentHashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(AnimalService.class).values().forEach(animal -> map.put(animal.getType(), animal));
    }

    public void sayHello(AnimalService animal){
        map.get(animal.getType()).sayHello();
    }

    public void sayHello(String type){
        if (type.equals("xiaoji")) {
            System.out.println("小鸡叫");
        }else if (type.equals("yazi")) {
            System.out.println("鸭子叫");
        }
    }
}

测试

@Test
void test() {
    AnimalService animal = new YaziServiceImpl();
    animalStrategyServiceFactory.sayHello(animal);
}

这种代码的好处是,如果以后要加个猪实现,是不需要修改代码的,即对修改关闭,对扩展开放。即开闭原则

你可能感兴趣的:(策略模式)