设计模式之Command

将客户端的请求传入一个对象,无需了解请求激活的动作或相关请求的处理细节,这样可以解耦发送者和接收者之间的联系,发送者调用一个操作,接收者接受操作请求执行相关的操作,这就是Command设计模式。将请求的命令封装在一个类中,然后调用者再对这个类进行操作,换句话说,本来是调用者是直接调用这些命令的,使用Command模式设计,在这两者之间添加一个中间者, 这样将直接关系就切断了,这样符合封装的特性,降低耦合度。

一、实现

典型的Command模式,需要有一个接口,调用者直接调用接口,接口的真正实现由另外的实现类来操作具体的细节。 

接口:

public interface ContextListenerWare {
	
	public void initialized(ServletContextEvent event);
	
	public void destroyed(ServletContextEvent event);

}
实现类:

public class DictService implements ContextListenerWare{
	@Override
	public void initialized(ServletContextEvent event) {
		loadingDicts();
	}

	@Override
	public void destroyed(ServletContextEvent event) {
		unLoadingDicts();		
	}
        ...
 }
调用类:

public class InitContextListener implements ServletContextListener{
	
	private String clazz = getClass().getName();
	private Logger logger=CommonLogger.logger;
	
	private static final Set<ContextListenerWare> initors;
	
	static{		
		initors = new HashSet<ContextListenerWare>();
	}
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		
		initors.add(new DictService());
                //多个ContextListenerWare的实现类的话,往initors里添加

                ContextListenerWare initor = null;
		for(Iterator<ContextListenerWare> it = initors.iterator(); it.hasNext() ;){
			initor = it.next();
			try{
				if(initor != null){
					initor.initialized(event);
				}
			}catch(Exception e){
				logger.error(clazz+":call "+initor.getClass().getName()+".initialized,occurs error:",e);
			}
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
		ContextListenerWare initor = null;
		for(Iterator<ContextListenerWare> it = initors.iterator(); it.hasNext() ;){
			initor = it.next();
			try{
				if(initor != null){
					initor.destroyed(event);
				}
			}catch(Exception e){
				logger.error(clazz+":call "+initor.getClass().getName()+".destroyed,occurs error:",e);
			}
		}
	}

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值