当前位置:   article > 正文

Java多线程相关知识【17】--设计模式--上下文模式(Context)_设计模式系列 上下文类

设计模式系列 上下文类


菜鸟的一个学习笔记,欢迎大神 批评指正

Java多线程相关知识【17】–设计模式–上下文模式(Context)

1. 问题的引入

线程在操作数据时,有很多时候要继续上一次操作的数据后才能进行本次的处理,为了解决这种办法,我们需要将一定的数据进行封装,在进行下次的处理,这既是上下文的处理模式。

2. 解决方法

1. 解决理论

​ 将相应的数据进行封装,然后进行相关的操作即可实现代码的利于维护性。

2. 实操代码

上下文数据保存
/**
 * 上下文数据保存
 */
public class Context {
   

    private String first;
    private String second;

    public String getFirst() {
   
        return first;
    }

    public void setFirst(String first) {
   
        this.first = first;
    }

    public String getSecond() {
   
        return second;
    }

    public void setSecond(String second) {
   
        this.second = second;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
上文
/**
 * 第一次查询
 */
public class FirstAction {
   
    private final String s="The first task:";

    public String exude(String key)  {
   
        try {
   
            Thread.sleep(100);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        return s+key;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
下文
/**
 * 连续查询
 */
public class SecondAction {
   
    private final String s="The second task:(";

    /**
     * 使用上一次结果查询本次内容
     * @param firstResult 上一次的结果
     * @return 查询的结果
     */
    public String exude(String firstResult){
   
        try {
   
            Thread.sleep(1000);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        return s+fir
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/948981
推荐阅读
相关标签
  

闽ICP备14008679号