访问者模式

定义:

定义一个访问者,去访问集合中不同类型的对象;集合中的每个对象都被定义成被访问者

要点:

集合中的每个对象都必须符合被访问者规范

实例:

1.定义被访问者行为规范

public interface Visible {
	
	public void accept( Visitor visitor ) throws Exception;

}

2.定义被访问者类型,这里定义了string和int两种类型

public class IntegerElement implements Visible {

	private final Integer value;
	
	public IntegerElement( Integer value ){
		this.value = value;
	}
	
	
	public Integer getValue(){
		return value;
	}
	
	@Override
	public void accept(Visitor visitor) throws Exception {
		// TODO Auto-generated method stub
		visitor.visitIntegerElement(this);
	}

}
public class StringElement implements Visible{
	
	private final String value;
	
	public StringElement( String value ){
		this.value = value;
	}
	
	
	public String getValue(){
		return value;
	}

	@Override
	public void accept(Visitor visitor) throws Exception {
		// TODO Auto-generated method stub
		visitor.visitStringElement(this);
	}
	
	


}

3.定义访问者规范

import java.util.Collection;

public interface Visitor {
	
	@SuppressWarnings("rawtypes")
	public void visitCollectionElement(Collection collection) throws Exception;

	public void visitIntegerElement(IntegerElement integerElement);

	public void visitStringElement(StringElement stringElement);

}

4.定义访问者类型

import java.util.Collection;
import java.util.Iterator;

public class DefaultVisitorImpl implements Visitor {

	@Override
	public void visitIntegerElement(IntegerElement integerElement) {
		// TODO Auto-generated method stub
		System.out.println(integerElement.getValue().intValue());
	}

	@Override
	public void visitStringElement(StringElement stringElement) {
		// TODO Auto-generated method stub
		System.out.println(stringElement.getValue());
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void visitCollectionElement(Collection collection) throws Exception {
		if( collection != null && !collection.isEmpty()){
			Iterator iterator = collection.iterator();
			while( iterator.hasNext() ){
				Visible visibleObj = (Visible)iterator.next();
				visibleObj.accept(this);
			}
		}
	}

}
5.测试

import java.util.ArrayList;
import java.util.List;

public class Test {

	/**
	 * @param args
	 * @throws Exception 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) throws Exception {
		StringElement se = new StringElement("string");
		IntegerElement ie = new IntegerElement(3);
		
		List list = new ArrayList();
		list.add(se);
		list.add(ie);
		
		Visitor visitor = new DefaultVisitorImpl();
		
		visitor.visitCollectionElement(list);
	}	

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值