1.定义责任链接口
package com.lpl.tank.cor;
import com.lpl.tank.GameObject;
/**
* @Classname Collider
* @Description 碰撞,责任链是实现该接口
* @Date 2021/2/2 21:07
* @Created by lplmbp
*/
public interface Collider {
boolean collide(GameObject o1,GameObject o2);
}
2.责任链类实现该接口
2.1私有的集合类(Linked)
2.2构造中有默认的过滤(集合中添加各种1中实现类)
2.3可以添加删除节点
package com.lpl.tank.cor;
import com.lpl.tank.GameObject;
import com.lpl.tank.PropertyMgr;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* @Classname ColliderChain
* @Description 责任链
* @Date 2021/2/2 21:44
* @Created by lplmbp
*/
public class ColliderChain implements Collider {
private List<Collider> colliders = new LinkedList<>();
public ColliderChain() {
String colliders = (String) PropertyMgr.get("colliders");
List<String> colliderList = Arrays.asList(colliders.split(","));
for (String collider : colliderList) {
try {
add((Collider) Class.forName(collider).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
// add(new BulletTankCollider());
// add(new TankTankCollider());
}
public void add(Collider c) {
colliders.add(c);
}
//具体的过滤
public boolean collide(GameObject o1, GameObject o2) {
for (int i = 0; i < colliders.size(); i++) {
if (!colliders.get(i).collide(o1, o2)) {
//如果某个链条件符合中止,则余下链不执行
return false;
}
}
return true;
}
}
3.普通责任链节点
package com.lpl.tank.cor;
import com.lpl.tank.Bullet;
import com.lpl.tank.GameObject;
import com.lpl.tank.Tank;
/**
* @Classname BulletTankCollider
* @Description TODO
* @Date 2021/2/2 21:10
* @Created by lplmbp
*/
public class BulletTankCollider implements Collider {
@Override
public boolean collide(GameObject o1, GameObject o2) {
if (o1 instanceof Bullet && o2 instanceof Tank) {
Bullet b = (Bullet) o1;
Tank t = (Tank) o2;
return b.collideWith(t);
} else if (o1 instanceof Tank && o2 instanceof Bullet) {
return collide(o2, o1);
}
return true;
}
}
public static void main(){
ColliderChain chain = new ColliderChain();
for (int i = 0; i < objects.size(); i++) {
objects.get(i).paint(g);
}
//碰撞检测
for (int i = 0; i < objects.size() ; i++) {
for (int j = i+1; j < objects.size(); j++) {
GameObject o1 = objects.get(i);
GameObject o2 = objects.get(j);
chain.collide(o1,o2);
}
}
}