4.1问题的解决方法
package test; public class Problem3 { public static void main(String[] args) { //访问者 IGamePersonPart gamePerson=new GamePerson(); gamePerson.accept(new GamePersonDisplayPartVisitor()); } } interface IGamePersonPart{ public void accept(GamePersonVisitor gamePersonVisitor); } class GamePerson implements IGamePersonPart{ IGamePersonPart[] decorates; //存储游戏人物配置 public GamePerson(){ decorates=new IGamePersonPart[]{new Clothes(),new Shoes(),new Accessories(),new Arms()}; } @Override public void accept(GamePersonVisitor gamePersonVisitor) { // TODO Auto-generated method stub for(int i=0;i<decorates.length;i++) { decorates[i].accept(gamePersonVisitor); } gamePersonVisitor.visit(this); } } class Clothes implements IGamePersonPart{ @Override public void accept(GamePersonVisitor gamePersonVisitor) { // TODO Auto-generated method stub gamePersonVisitor.visit(this); } } class Shoes implements IGamePersonPart{ @Override public void accept(GamePersonVisitor gamePersonVisitor) { // TODO Auto-generated method stub gamePersonVisitor.visit(this); } } class Accessories implements IGamePersonPart{ @Override public void accept(GamePersonVisitor gamePersonVisitor) { // TODO Auto-generated method stub gamePersonVisitor.visit(this); } } class Arms implements IGamePersonPart{ @Override public void accept(GamePersonVisitor gamePersonVisitor) { // TODO Auto-generated method stub gamePersonVisitor.visit(this); } } interface GamePersonVisitor { public void visit(GamePerson gamePerson); public void visit(Clothes clothes); public void visit(Shoes shoes); public void visit(Accessories accessories); public void visit(Arms arms); } //游戏人物和细节展示 class GamePersonDisplayPartVisitor implements GamePersonVisitor { @Override public void visit(GamePerson gamePerson) { System.out.println("Displaying GamePerson."); } @Override public void visit(Clothes clothes) { System.out.println("Displaying Clothes."); } @Override public void visit(Shoes shoes) { System.out.println("Displaying Shoes."); } @Override public void visit(Accessories accessories) { System.out.println("Displaying Accessories."); } @Override public void visit(Arms arms) { System.out.println("Displaying Arms."); } }