测试用四个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!