GoF23 之 责任链模式

 责任链模式是行为模式的一种

责任链模式 :当处理户端发起的一个请求时,通过一串对象来处理他们,而达到的一种松耦合软件设计的目的

 对请求有责任处理的多个类组成的链,如请假审批流程、采购审批流程。

  1.  当代码由很多个if else时,可以用责任链重构
  2. 请求处理方法在后续的需求大概率会新增时

优点
解耦 请求和请求处理分开
单一职责 每个处理类只需关心自己的业务,不需要知道下个处理是谁
符合开闭原则 新增处理方法简单

缺点
多个链路处理效率不高,单个处理会影响整体速度。
会存在无效遍历,空循环
容易写成死循环

举个栗子 过滤诗歌  1去除空格 2格式化 3提取名句

上代码

public abstract  class Handle {

   protected Handle next;


   public void next(Handle next){
       this.next = next;
   }

   public abstract void handle(Poetry poetry);

}
public class SpaceHandle extends Handle {
    @Override
    public void handle(Poetry poetry) {
        System.out.println("---------去除空格--------------");
        String content = poetry.getContent().replace(" ", "");
        poetry.setContent(content);
        System.out.println(content);
        next.handle(poetry);
    }
}
public class FormatHandle extends Handle {
    @Override
    public void handle(Poetry poetry) {
        System.out.println("---------格式化--------------");
        String content = poetry.getContent();
        String[] a = content.split("。");
        System.out.println("       "+poetry.getTitle());
        System.out.println("        "+poetry.getAuthor());
        Arrays.stream(a).forEach(b->{
            System.out.print(b);
            System.out.println("。");
        });
        this.next.handle(poetry);
    }
}

public class FamousSentenceHandle  extends Handle {

    @Override
    public void handle(Poetry poetry) {
        System.out.println("---------名句提取--------------");
        String content = poetry.getContent();
        String[] cons = content.split("。");
        String famous = cons[1].toString();
        System.out.println();
        System.out.println(famous);
    }

}
@Data
public class Poetry {

    Poetry(String author,String content,String title){
        this.author = author;
        this.content = content;
        this.title = title;
    }
    String author;
    String content;
    String title;
}

测试类

public class Test {
    public static void main(String[] args) {
        Poetry poetry = new Poetry("陆游", "  莫笑农家腊酒浑,丰年留客足鸡豚。 山重水复疑无路,柳暗花明又一村。箫鼓追随春社近, 衣冠简朴古风存。从今若许闲乘月,拄杖无时夜叩门。", "游山西村");
        SpaceHandle spaceHandle = new SpaceHandle();
        FormatHandle formatHandle = new FormatHandle();
        FamousSentenceHandle famousSentenceHandle = new FamousSentenceHandle();

        spaceHandle.next(formatHandle);
        formatHandle.next(famousSentenceHandle);
        System.out.println("---------原句--------------");
        System.out.println(poetry.getContent());
        spaceHandle.handle(poetry);
    }
}

执行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值