策略模式
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 策略模式 {
public static void main(String[] args) {
Context context = new Context(new 微信支付());
context.收钱();
context.付钱();
}
}
interface 支付{
void 付钱();
void 收钱();
}
class 微信支付 implements 支付{
@Override
public void 付钱() {
System.out.println("微信付钱");
}
@Override
public void 收钱() {
System.out.println("微信收钱");
}
}
class 支付宝支付 implements 支付{
@Override
public void 付钱() {
System.out.println("支付宝付钱");
}
@Override
public void 收钱() {
System.out.println("支付宝收钱");
}
}
class Context{
private 支付 pay;
public Context(支付 payWay) {
this.pay = payWay;
}
public void 付钱() {
pay.付钱();
}
public void 收钱() {
pay.收钱();
}
}
- 优点
- 上下文和具体策略是松耦合关系。
- 策略模式满足"开闭原则",当新增具体策略时不需修改上下文代码。
- 场景
- 如果程序不希望暴露内部细节,可以使用策略模式封装
- 应用
-
Arrays.sort(Object[],Comparator)
和Collections.sort(List,Comparator)
/** * @USER: lynn * @DATE: 2020/4/26 **/ public class 策略模式 { public static void main(String[] args) { Integer[] integers = { new Integer(1), new Integer(3), new Integer(5) } ; Arrays.sort(integers,new Comparator(){ @Override public int compare(Object o1, Object o2) { return ((Integer) o2).intValue()-((Integer) o1).intValue(); } }); System.out.println(Arrays.toString(integers)); } }
-
使用Lambda表达式简化策略模式
前提:函数接口(@FunctionalInterface)
/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class 策略模式 {
public static void main(String[] args) {
Context context = new Context((int money)->{
System.out.println("微信付钱"+money);
});
context.付钱(100);
}
}
@FunctionalInterface
interface 支付{
void 付钱(int money);
}
class Context{
private 支付 pay;
public Context(支付 payWay) {
this.pay = payWay;
}
public void 付钱(int money) {
pay.付钱(money);
}
}