应用:责任链模式在SringSecurity的一系列过滤链和多种provider检验多种登陆方式中用到
类图
创建容器的抽象类或者接口
package com.wwj.tank;
public abstract class Collider {
public abstract boolean collide(GameObject o1, GameObject o2);
}
添加具体的一个实现类
package com.wwj.tank;
public class BullertTankCollider extends Collider{
@Override
public boolean collide(GameObject o1, GameObject o2) {
if (o1 instanceof Bullert && o2 instanceof Tank){
Bullert bullert = (Bullert)o1;
Tank tank = (Tank)o2;
if(bullert.getGroup() == tank.getGroup()){
return true;
}
if(bullert.getRect().intersects(tank.rect)){
bullert.die();
tank.die();
int bx = tank.getX() + Tank.WIDTH/2 - Expode.WIDTH/2;
int by = tank.getY() + Tank.WIDTH/2 - Expode.WIDTH/2;
GameMode.getInstance().add(new Expode(bx,by));
return false;
}
}else if(o1 instanceof Tank && o2 instanceof Bullert){
collide(o2,o1);
}
return false;
}
}
定义链类,同时继承或实现定义的接口
package com.wwj.tank;
import java.util.LinkedList;
/**
* 碰撞检测链
*/
public class ColliderChain extends Collider{
private LinkedList<Collider> colliders = new LinkedList<>();
public ColliderChain(){
colliders.add(new BullertTankCollider());
}
@Override
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 false;
}
}
调用责任链
package com.wwj.tank;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
/**
* @author wwj
*/
public class GameMode extends Frame {
private static final GameMode instance = new GameMode();
private ArrayList<GameObject> gameObjects = new ArrayList<>();
ColliderChain colliderChain = new ColliderChain();
public void add(GameObject gameObject){
this.gameObjects.add(gameObject);
}
public void remove(GameObject gameObject){
this.gameObjects.remove(gameObject);
}
private GameMode(){
this.setSize(GAMEWIDTF,GAMEHEIGHT);
this.setResizable(false);
this.setTitle("Tank Game");
this.setVisible(true);
this.addKeyListener(new MyKeyListing());
this.setBackground(Color.BLACK);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static GameMode getInstance(){
return instance;
}
@Override
public void paint(Graphics g){
//画出界面提示
g.setColor(Color.WHITE);
//将元素全部画出
myTank.paint(g);
for(int index = 0; index < gameObjects.size();index++){
gameObjects.get(index).paint(g);
}
//子弹与坦克的碰撞检测
for (int i = 0; i < gameObjects.size(); i++) {
for (int j = i+1; j < gameObjects.size(); j++) {
GameObject o1 = gameObjects.get(i);
GameObject o2 = gameObjects.get(j);
colliderChain.collide(o1,o2);
}
}
}
}
好处:后续的碰撞都聚集在这条链中,新增物体和碰撞方式都只需要新增实现类即可,高内聚