---
title: "责任链模式"
author: "SunSteven"
date: "2012-09-30T22:41:00Z"
tags: []
categories: ["开源软件"]
slug: "untitled"
draft: false
lastmod: "2012-09-30T22:41:00Z"
id: 1688992
url: "https://sunsteven.iteye.com/blog/1688992"
---

Descriptor可称为构造者。负责责任链的列表建设，并返回一个链头。

public class CommandServiceDescriptor extends AbstractDescriptor {

  private static final long serialVersionUID = 1L;
  
  CommandService commandService;
  List<Descriptor> interceptorDescriptors;

  public Object construct(WireContext wireContext) {
    CommandService interceptedCommandService = commandService;
    if (interceptorDescriptors!=null) {
      for (int i=interceptorDescriptors.size()-1 ; i>=0; i--) {
        Descriptor descriptor = interceptorDescriptors.get(i);
        Interceptor interceptor = (Interceptor) descriptor.construct(wireContext);
        interceptor.setNext(interceptedCommandService);
        interceptedCommandService = interceptor;
      }
    }
    return interceptedCommandService;
  }


下面是解析xml，然后到责任链的列表集合

public class CommandServiceBinding extends WireDescriptorBinding {

  public CommandServiceBinding() {
    super("command-service");
  }
  
  protected CommandServiceBinding(String tagName) {
    super(tagName);
  }

  public Object parse(Element element, Parse parse, Parser parser) {
    CommandServiceDescriptor commandServiceDescriptor = new CommandServiceDescriptor();

    CommandService commandService = getCommandService(element, parse, parser);
    commandServiceDescriptor.setCommandService(commandService);
    
    List<Element> interceptorElements = XmlUtil.elements(element);
    for (Element interceptorElement : interceptorElements) {
      Descriptor interceptorDescriptor = (Descriptor) parser.parseElement(interceptorElement, parse, WireParser.CATEGORY_INTERCEPTOR);
      commandServiceDescriptor.addInterceptorDescriptor(interceptorDescriptor);
    }

parse类中的方法

 public Object parseElement(Element element, Parse parse, String category) {
    Object object = null;
    String tagName = element.getLocalName();

    Binding binding = getBinding(element, category);

    if (binding != null) {
      object = binding.parse(element, parse, this);
    }
    else if (log.isDebugEnabled()) {
      log.debug("no element parser for tag " + tagName
        + (category != null ? " in category " + category : " in the default category"));
    }

    return object;
  }