设计模式-行为型模式讲解一(责任链、命令、迭代器)

举报
小毕超 发表于 2022/06/23 22:15:20 2022/06/23
【摘要】 一、行为型设计模式 上篇,我们呢讲解了结构型设计模式,包括 适配器模式、桥接模式、组合模式、装饰者模式、享元模式、代理模式、外观模式。 文章地址(适配器、桥接、组合、享元):https://bl...

一、行为型设计模式

上篇,我们呢讲解了结构型设计模式,包括 适配器模式、桥接模式、组合模式、装饰者模式、享元模式、代理模式、外观模式。

文章地址(适配器、桥接、组合、享元):https://blog.csdn.net/qq_43692950/article/details/120248267
文章地址( 装饰者、外观、代理):https://blog.csdn.net/qq_43692950/article/details/120249265

这篇文章我们来讲解下行为型设计模式:主要用于描述类或对象之间的交互或职责的分配,为设计类的交互和职责分配做指南。

在本文主要介绍:责任链、命令、迭代器模式。

二、责任链模式

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。

在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

优点是降低了耦合度,它将请求的发送者和接收者解耦。简化了对象,使得对象不需要知道链的结构。 增强给对象指派职责的灵活性,通过改变链内的成员或者调动它们的次序,允许动态地新增或者删除责任。 增加新的请求处理类很方便。

举个例子:在平时开发中,我们经常需要打印日志来查看一些信息,但打日志时我们都会指定一个日志级别,比如 INFO、WARN、ERROR等,指定不同的级别打印的日志存储的文件是不同的,这种场景就可以使用责任链设计模式来设计解决。

下面使用程序演示下上面的例子:

  1. 定义日志接口
public interface LoggerInterFace {
    //指定下一个目标
    void setNextLogger(LoggerInterFace nextLogger);
    //打印日志
    void logMessage(int level, String message);
    //日志格式
    void writeFormat(String message);
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 定义日志抽象模板
public abstract class AbstractLogger implements LoggerInterFace {
    public static int INFO = 1;
    public static int WARN = 2;
    public static int ERROR = 3;

    private int level;
    private LoggerInterFace nextLogger;

    public AbstractLogger(int level) {
        this.level = level;
    }

    @Override
    public void setNextLogger(LoggerInterFace nextLogger) {
        this.nextLogger = nextLogger;
    }

    @Override
    public void logMessage(int level, String message) {
        if (this.level == level) {
            writeFormat(message);
        }
        if (nextLogger != null) {
            nextLogger.logMessage(level, message);
        }
    }

}

  
 
  • 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
  1. 定义Info级别的实现
public class InfoLogger extends AbstractLogger {

   public InfoLogger(int level) {
      super(level);
   }

   @Override
   public void writeFormat(String message) {
      System.out.println(StringFormatter.concat(" 普通信息:", message).getValue());
   }

}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  1. 定义Warn级别的实现
public class WarnLogger extends AbstractLogger {

   public WarnLogger(int level) {
      super(level);
   }

   @Override
   public void writeFormat(String message) {
      System.out.println(StringFormatter.concat(" 警告信息:", message).getValue());
   }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 定义Error级别的实现
public class ErrorLogger extends AbstractLogger {

    public ErrorLogger(int level) {
        super(level);
    }

    @Override
    public void writeFormat(String message) {
        System.out.println(StringFormatter.concat(" 错误信息:", message).getValue());
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 定义日志工厂,定义责任链的顺序
public class LoggerFactory {

    public static LoggerInterFace getLogger() {
        //定义责任链的顺序
        List<AbstractLogger> list = new LinkedList<>();
        list.add(new ErrorLogger(AbstractLogger.ERROR));
        list.add(new WarnLogger(AbstractLogger.WARN));
        list.add(new InfoLogger(AbstractLogger.INFO));

        for (int i = 0; i < list.size() - 1; i++) {
            list.get(i).setNextLogger(list.get(i + 1));
        }

        return list.get(0);
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  1. 演示
public class demo {
    public static void main(String[] args) {
        LoggerInterFace logger = LoggerFactory.getLogger();

        logger.logMessage(AbstractLogger.INFO, " 打印普通日志");

        logger.logMessage(AbstractLogger.WARN, " 打印警告日志");

        logger.logMessage(AbstractLogger.ERROR, " 打印错误日志");
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

三、命令模式

命令模式(Command Pattern)是一种数据驱动的设计模式,请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

优点是降低了系统耦合度,新的命令可以很容易添加到系统中去。

还是用原先画各种形状的例子来说,我们可以采用命令设计模式来设计,绘画不同的形状就将对应形状的实现传递给命令执行器,以一种统一的命令的形式来做不同的操作。可以有效降低耦合性和提高扩展性。

下面使用程序演示下:

  1. 定义形状接口
public interface ShapeInterFace {
    void draw();
}

  
 
  • 1
  • 2
  • 3
  1. 定义绘制圆形的实现
public class CircleShape implements ShapeInterFace {
    @Override
    public void draw() {
        System.out.println("画圆形");
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 定义绘制矩形的实现
public class RectangleShape implements ShapeInterFace {
    @Override
    public void draw() {
        System.out.println("画矩形!");
    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 定义命令接口
public interface CommandInterFace {
    void execute();
}

  
 
  • 1
  • 2
  • 3
  1. 定义命令抽象模板
public abstract class CommandAbstract implements CommandInterFace {
    protected ShapeInterFace shape;

    public CommandAbstract(ShapeInterFace shape) {
        this.shape = shape;
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 定义形状命令的实现
public class ShapeCommand extends CommandAbstract {

    public ShapeCommand(ShapeInterFace shape) {
        super(shape);
    }

    @Override
    public void execute() {
        shape.draw();
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 定义命令执行器
public class Invoker {
    private CommandInterFace command;

    public void setCommand(CommandInterFace command) {
        this.command = command;
    }

    public void executeCommand() {
        command.execute();
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 演示
public class demo {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        invoker.setCommand(new ShapeCommand(new CircleShape()));
        invoker.executeCommand();

        invoker.setCommand(new ShapeCommand(new RectangleShape()));
        invoker.executeCommand();
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

四、迭代器模式

迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。优点它支持以不同的方式遍历一个聚合对象。迭代器简化了聚合类。 在同一个聚合上可以有多个遍历。 在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码。

下面我们使用程序看下迭代器的设计过程:

  1. 定义迭代器接口
public interface Iterator {
   public boolean hasNext();
   public Object next();
}

  
 
  • 1
  • 2
  • 3
  • 4
  1. 定义迭代器的实现
public class NameIterator implements Iterator {
    private int index;
    private String[] names;

    public NameIterator(String[] names) {
        this.names = names;
    }

    @Override
    public boolean hasNext() {
        if (index < names.length) {
            return true;
        }
        return false;
    }

    @Override
    public Object next() {
        if (this.hasNext()) {
            return names[index++];
        }
        return null;
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  1. 演示
public class demo {
   public static void main(String[] args) {
      String[] names = {"A" , "B" ,"C" , "D"};

      NameIterator iterator = new NameIterator(names);
      while (iterator.hasNext()){
         String name = (String)iterator.next();
         System.out.println(name);
      }
   }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

文章来源: blog.csdn.net,作者:小毕超,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/qq_43692950/article/details/120404903

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。