策略模式
/**
* @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.收錢();
}
}
- 優(yōu)點
- 上下文和具體策略是松耦合關(guān)系。
- 策略模式滿足"開閉原則",當(dāng)新增具體策略時不需修改上下文代碼。
- 場景
- 如果程序不希望暴露內(nèi)部細(xì)節(jié),可以使用策略模式封裝
- 應(yīng)用
-
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表達(dá)式簡化策略模式
前提:函數(shù)接口(@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);
}
}