装饰模式

什么是装饰模式

哈喽,大家好,我是花臂,今天给大家讲一下装饰模式的案例实战

装饰模式,顾名思义,就是给一个类加一些装饰,增加一些新的功能,而且不影响以前的功能,也不用改动以前功能的代码,就像人冷了加衣服一样,不用动里面的衣服。

主要角色:

  1. 抽象类或接口
  2. 具体的被装饰类
  3. 装饰类
  4. 具体的装饰器类

装饰模式的应用场景

  1. mybatis的二级缓存
  2. 企业项目多级缓存

具体代码实现

实现一个三级缓存

!Commonts接口

public interface  Commonts {

 public  Object getEache(Object key);//查询数据
 public  void putEache(String key,String value);//往缓存里面放数据

}

!被装饰的类(OneEache一级缓存)

/***
 *一级缓存
 */
public class OneEache implements Commonts {

 //模拟一级缓存数据
 Map<String, String> map = new HashMap<String, String>();

 public OneEache() {
  map.put("one", "测试数据");
 }

 public Object getEache(Object key) {
  System.out.println("查询一级缓存数据");
  String s = map.get(key);
  return s;
 }

 public void putEache(String key, String value) {

 }
}

!装饰类

/***
 * 抽象的装饰者
 */
public   class DecoratorComon implements Commonts {

 public Object getEache(Object key) {
  Object eache = commonts.getEache(key);
  return eache;
 }

 public void putEache(String key, String value) {

 }

 protected Commonts commonts;

 public DecoratorComon(Commonts commonts) {
  this.commonts=commonts;
 }
}

!具体的装饰类1

/***
 * 二级缓存
 */
public class TwoEache extends DecoratorComon {
 Map<Object, Object> map = new HashMap<Object, Object>();

 public TwoEache(OneEache oneEache) {
  super(oneEache);
 }

 public Object getEache(Object key) {
  System.out.println("查询二级缓存数据");
  //先查询二级缓存
  Object towValue = map.get(key);
  if (towValue == null) {
   //如果二级缓存没有再查询一级缓存
   Object OneValue = super.getEache(key);
   towValue=OneValue;
   //然后将一级缓存的值存储到二级缓存中
   map.put(key,OneValue);
  }
  return towValue;
 }

 public void putEache(String key, String value) {

 }
}

!具体的装饰类2

/***
*三级缓存
*/
public class ThreeEache extends DecoratorComon {
 Map map = new HashMap();//模拟三级缓存

 @Override
 public Object getEache(Object key) {
  System.out.println("查询三级缓存");
  //查询三级缓存
  Object threeValue = map.get(key);
  if (threeValue == null) {
   //三级缓存没有查询二级缓存
   Object twoValue = super.getEache(key);
   threeValue = twoValue;
   //设置三级缓存
   map.put(key, threeValue);

  }
return threeValue;
 }

 @Override
 public void putEache(String key, String value) {
  super.putEache(key, value);
 }

 public ThreeEache(Commonts commonts) {
  super(commonts);
 }
}

!测试类

public class FactroyTest {

 public static Commonts getCommons(){
 return new ThreeEache(new TwoEache(new OneEache()));
 }

 public static void main(String[] args) {
  Commonts commons = getCommons();
  Object one = commons.getEache("one");
  System.out.println(one);
  Object one2 = commons.getEache("one");
  System.out.println(one2);
 }
}

测试

ok,本次教程就到这,有什么疑问欢迎下方评论区留言!

本文参考蚂蚁课堂

评论区



© [2020] · Powered by Typecho · Theme by Morecho
鄂ICP备20005123号