重构:重复代码(NIO中的粒度细分)

ServerSocketChannel 只能把OP_ACCEPT注册到某个Selector上,不能注册OP_CONNENCT,OP_READ,OP_WRITE事件;
而SocketChannel 恰恰相反,它能注册OP_CONNENCT,OP_READ,OP_WRITE事件,不能注册OP_ACCEPT。
但是,将某种Channel注册到某个Selector的操作绝大多数都是一样的,也就是说我们可以在超类中实现这些东西。

Bad smells in code中有提过“Duplicated code”,其中一种情况就是重复的代码出现在两个兄弟类中,我们应该把
共同的部分Pull up到超类中去,对于他们之间的不同部分,应该单独出来,细化成某个粒度更小的接口或抽象方法,以在
不同子类中不同实现。

 

SuperClass {

protected abstart void diffPart();
public  void operation() {
    //共同操作
 diffPart();
    //共同操作
}

}

 

SubClassOne {
 public void diffPart() {
    //subClassOne's part 
 }
}

 

SubClassTwo {
 public void diffPart() {
  //subClassTwo's part
 }
}

 

public abstract int validOps();//超类中细粒度的抽象方法
public final SelectionKey register(Selector sel, int ops,
				       Object att)
	throws ClosedChannelException
    {
	if (!isOpen())
	    throw new ClosedChannelException();
	if ((ops & ~validOps()) != 0)//各个子类不同的部分
	    throw new IllegalArgumentException();
	synchronized (regLock) {
	    if (blocking)
		throw new IllegalBlockingModeException();
	    SelectionKey k = findKey(sel);
            if (k != null) {
                k.interestOps(ops);
		k.attach(att);
            }
	    if (k == null) {
		// New registration
		k = ((AbstractSelector)sel).register(this, ops, att);
		addKey(k);
	    }
            return k;
        }
    }

子类 SocketChannel的实现:

 /**
     * Returns an operation set identifying this channel's supported
     * operations.
     *
     * <p> Socket channels support connecting, reading, and writing, so this
     * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
     * <tt>|</tt> {@link SelectionKey#OP_READ} <tt>|</tt> {@link
     * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
     *
     * @return  The valid-operation set
     */
    public final int validOps() {
	return (SelectionKey.OP_READ
		| SelectionKey.OP_WRITE
		| SelectionKey.OP_CONNECT);
    }

 

子类ServerSocketChannel的实现:

/**
     * Returns an operation set identifying this channel's supported
     * operations.
     *
     * <p> Server-socket channels only support the accepting of new
     * connections, so this method returns {@link SelectionKey#OP_ACCEPT}.
     * </p>
     *
     * @return  The valid-operation set
     */
    public final int validOps() {
	return SelectionKey.OP_ACCEPT;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值