链式实现dome

测试用四个java类:ChainAble.java;ChainServer.java;Chain1.java;Chain2.java

其中接口:ChainAble:

package com.szy.project.chain.able;

public interface ChainAble {

	String doOperation();
}

ChainServer:

package com.szy.project.chain.server;

import java.util.concurrent.ConcurrentHashMap;

import com.szy.project.chain.able.ChainAble;
import com.szy.project.chain.impl.Chain1;
import com.szy.project.chain.impl.Chain2;

public abstract class ChainServer implements ChainAble{

	static ConcurrentHashMap<Integer, ChainAble> chainMap = new ConcurrentHashMap<Integer, ChainAble>();
	
	public ChainServer(int type){
		chainMap.put(type, this);
	}
	
	public static ChainAble getServer(int type){
		ChainAble chain = chainMap.get(type);
		if(chain == null){
			 if(type == 1)
				 chain =  new Chain1(type);
			 else if(type==2)
				 chain = new Chain2(type);
		}
		return chain;
	}
	
}

Chain1:

package com.szy.project.chain.impl;

import com.szy.project.chain.server.ChainServer;

public class Chain1 extends ChainServer{

	public Chain1(int type) {
		super(type);
	}

	public String doOperation() {
		return "This is Test1's Server!";
	}

}

Chain2

package com.szy.project.chain.impl;

import com.szy.project.chain.server.ChainServer;

public class Chain2 extends ChainServer{

	public Chain2(int type) {
		super(type);
	}

	public String doOperation() {
		return "This is Test2's Server!";
	}

}

测试:

@Test
	public void test1(){
		int type = 1;
		System.out.println(ChainServer.getServer(type).doOperation());
		type = 2;
		System.out.println(ChainServer.getServer(type).doOperation());
	}

输出:

This is Test1's Server!
This is Test2's Server!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值