策略模式

1. 简介

  客户端根据实际的场景,选择不同的策略完成工作;

  不同测策略完成的都是相同的任务,只不过完成任务的方式不同;

  具体的策略由客户端来选择;

2. 代码实现

/**
 * @Describe: 策略接口
 * @Author: chenfan
 * @Date: 2020/4/16 20:05
 */
public interface Strategy {

    void execute();
}

/**
 * @Describe: 有钱的时候
 * @Author: chenfan
 * @Date: 2020/4/16 20:06
 */
public class Rich implements Strategy {

    @Override
    public void execute() {
        System.out.println("有钱的日子,大口吃肉,大口喝酒");
    }
}

/**
 * @Describe: 没钱的时候
 * @Author: chenfan
 * @Date: 2020/4/16 20:07
 */
public class Poor implements Strategy {

    @Override
    public void execute() {
        System.out.println("没钱的日子,来一碗泡面");
    }
}

/**
 * @Describe: 执行者,组合了一个策略对象
 * @Author: chenfan
 * @Date: 2020/4/16 20:08
 */
@Data
@AllArgsConstructor
public class Context {

    private Strategy strategy;

    public void run(){
        strategy.execute();
    }
}

**
 * @Describe: 客户端
 * @Author: chenfan
 * @Date: 2020/4/16 20:11
 */
public class Client {

    public static void main(String[] args) {

        /**
         *  客户端决定什么场景下用什么策略
         *  执行者根据不同的策略执行不同的行为,完成相同的工作
         */
        Strategy strategy = new Rich();
        Context context = new Context(strategy);
        context.run();

        strategy = new Poor();
        context = new Context(strategy);
        context.run();

    }
}
原文地址:https://www.cnblogs.com/virgosnail/p/12715469.html