Java模式之责任链

今天模仿tomcat的Filter,自己学着写了一个测试例子。没有实现init和destroy方法,后期有时间再完善吧。

首先定义Filter的抽象接口

package com.learning.chain;

public interface Filter {

	public void init();
	
	public void doFilter(FilterChain chain);
	
	public void destroy();
}

 然后定义Filter配置类

package com.learning.chain;

public class ApplicationFilterConfig {

	private Filter filter;

	public Filter getFilter() {
		return filter;
	}

	public void setFilter(Filter filter) {
		this.filter = filter;
	}
	
}

 然后提取责任链抽象接口

package com.learning.chain;

public interface FilterChain {
	public void doFilter();
}

 实现责任链抽象接口

package com.learning.chain;

public class ApplicationFilterChain implements FilterChain {

	private ApplicationFilterConfig[] filters = new ApplicationFilterConfig[0];
	
	private static int INCREMENT = 10;
	
	private int length = 0;
	
	private int pos = 0;
	
	void addFilter(ApplicationFilterConfig filterConfig) {
		if (length == filters.length) {
            ApplicationFilterConfig[] newFilters =
                new ApplicationFilterConfig[length + INCREMENT];
            System.arraycopy(filters, 0, newFilters, 0, length);
            filters = newFilters;
        }
        filters[length++] = filterConfig;
	}
	
	public void doFilter() {
		if (pos < length) {
			ApplicationFilterConfig filterConfig = filters[pos++];
			Filter filter = filterConfig.getFilter();
			filter.doFilter(this);
		}
	}
	
}

 实现责任链工厂类

package com.learning.chain;

public class ApplicationFilterFactory {

	private static ApplicationFilterFactory factory;
	
	public static ApplicationFilterFactory getInstance() {
		if (factory == null) {
			factory = new ApplicationFilterFactory();
		}
		return factory;
	}
	
	public ApplicationFilterChain createFilterChain() {
		return new ApplicationFilterChain();
	}
	
}

 写测试用例

package com.learning.chain;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.junit.Test;

public class TestFilter {

	@Test
	public void test() throws Exception {
		// 创建过滤器责任链
		ApplicationFilterChain chain = ApplicationFilterFactory.getInstance().createFilterChain();
		
		File file = new File("chain.properties");
		Properties filterProperties = new Properties();
		// 载入过滤器
		filterProperties.load(new FileInputStream(file));
		
		Enumeration<?> names = filterProperties.propertyNames();
		while (names.hasMoreElements()) {
			String filterName = (String)filterProperties.get(names.nextElement());
			ApplicationFilterConfig filterConfig = new ApplicationFilterConfig();
			filterConfig.setFilter((Filter)Class.forName(filterName).newInstance());
			// 把过滤器加入到责任链中
			chain.addFilter(filterConfig);
		}
		
		// 开始执行
		chain.doFilter();
	}
}

 最后配置好配置文件

filter1=com.learning.chain.FilterA
filter2=com.learning.chain.FilterA
filter3=com.learning.chain.FilterB
filter4=com.learning.chain.FilterA

 ok,运行起了,效果还不错。。。

你可能感兴趣的:(java模式)