【设计模式之策略模式】

一世执手 提交于 2020-03-15 17:48:55

1、策略模式(Strategy) 将定义的算法家族、分别封装起来,让他们之间可以互相替换,从而让算法的变化不会影响到使用算法的用户。
   策略模式属于 行为性模式
   
2、实现方式

   
   Context上下文
   Context 封装角色,起承上启下的作用,屏蔽高层模块对策略、算法的直接访问,封装可能存在的变化。
   

/**
 * @Author: Liu 
 * @Descripition:
 * @Date; Create in 2020/3/14 20:31
 **/
public class Context {

    private IStrategy iStrategy ;

    public Context(IStrategy iStrategy){
        this.iStrategy = iStrategy;
    }
    //上下文
    public void algorithm(){
        iStrategy.algorithm();
    }
}


   策略角色
   抽象策略角色,是对策略、算法家族的抽象,通常为接口,定义每个策略或算法必须具有的方法和属性。
   

/**
 * @Author: Liu 
 * @Descripition:
 * @Date; Create in 2020/3/14 20:26
 **/
public interface IStrategy {
    void algorithm();
}


   具体策略角色
   用于实现抽象策略中的操作,即实现具体的算法 
   

/**
 * @Author: Liu 
 * @Descripition:
 * @Date; Create in 2020/3/14 20:28
 **/
public class IStrategyAImpl implements IStrategy {
    @Override
    public void algorithm() {
        System.out.println("策略 aaaa");
    }
}

public class IStrategyBImpl implements IStrategy {
    @Override
    public void algorithm() {
        System.out.println("策略 BBB");
    }
}


   client客户端
   

/**
 * @Author: Liu 
 * @Descripition:
 * @Date; Create in 2020/3/14 20:34
 **/
public class strategyTest {

    public static void main(String[] args) {
        Context context = new Context(new IStrategyAImpl());
        context.algorithm();
        Context context = new Context(new IStrategyBImpl());
        context.algorithm();
 
    }
}


   
每日提高一点点

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!