Java设计模式从精通到入门三 策略模式

介绍

我尽量用最少的语言解释总结:

Java23种设计模式之一,属于行为型模式。一个类的行为或者算法可以在运行时更改,策略对象改变context对象执行算法。

应用实例:

​ 以周瑜赔了夫人又折兵的例子。

uml类图如下

5c27396ec7bf4.png

主要代码如下

策略接口

/**
 * @ClassName Stragety
 * @Description 策略抽象类
 * @Author ouyangkang
 * @Date 2018-11-15 09:06
 **/
public interface Stragety {

    void operation();
}

策略接口实现类

/**
 * @ClassName BackDoorStragety
 * @Description 乔国老开后门
 * @Author ouyangkang
 * @Date 2018-11-15 09:14
 **/
public class BackDoorStragety implements Stragety {

    @Override
    public void operation() {
        System.out.println("拜访乔国老,请求开后门");
    }
}
/**
 * @ClassName GreenLightStragety
 * @Description 吴国太开绿灯
 * @Author ouyangkang
 * @Date 2018-11-15 09:16
 **/
public class GreenLightStragety implements Stragety {
    @Override
    public void operation() {
        System.out.println("拜访吴国太,请求开绿灯");
    }
}

/**
 * @ClassName PostBreakStragety
 * @Description 孙夫人断后
 * @Author ouyangkang
 * @Date 2018-11-15 09:18
 **/
public class PostBreakStragety implements Stragety {
    @Override
    public void operation() {
        System.out.println("拜访孙夫人,请求断后");
    }
}

context类


/**
 * @ClassName Context
 * @Description 策略执行
 * @Author ouyangkang
 * @Date 2018-11-15 09:18
 **/
public class Context {

    private Stragety stragety;

    public Context(Stragety stragety){
        this.stragety = stragety;
    }

    public void operation(){
        this.stragety.operation();
    }
}

main


/**
 * @ClassName Main
 * @Description TODO
 * @Author ouyangkang
 * @Date 2018/9/25 11:22
 **/
public class Main {

    public static void main(String[] args) {
        System.out.println("去往吴国, 刘备慌得一匹,赵云打开第一个锦囊");
        Context backDoor = new Context(new BackDoorStragety());
        backDoor.operation();

        System.out.println("--------------");

        System.out.println("刘备在吴国还不是美滋滋,美酒,美人, 赵云打开第二个锦囊");
        Context greenLight = new Context(new GreenLightStragety());
        greenLight.operation();

        System.out.println("--------------");

        System.out.println("准备撤了,赵云打开第三个精囊");
        Context postBreak = new Context(new PostBreakStragety());
        postBreak.operation();

        System.out.println("诸葛亮气死周瑜");
    }
}

执行结果:

去往吴国, 刘备慌得一匹,赵云打开第一个锦囊
拜访乔国老,请求开后门
--------------
刘备在吴国还不是美滋滋,美酒,美人, 赵云打开第二个锦囊
拜访吴国太,请求开绿灯
--------------
准备撤了,赵云打开第三个精囊
拜访孙夫人,请求断后
诸葛亮气死周瑜

总结

可以用策略模式代替过多的if else。更加的灵活

转载于:https://www.cnblogs.com/Krloypower/p/9961730.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值