public interface PlayBall {
public void playBall( String ballName); //玩球
}
2、玩具体的球(PlayConcreteBall)是对玩球(PlayBall)接口的具体实现:
public class PlayConcreteBall implements PlayBall{
public void playBall(String concreteBallName) {
System.out.println("玩"+concreteBallName+"!");
}
}
3、定义体育馆(Gymnasium)类:
public class Gymnasium {
private Hashtable playBallList = new Hashtable(); //体育馆根据我们的需要填写的选球清单
public PlayBall getPlayBall(Object key) { //得到要玩的球
PlayBall playBall = (PlayBall) playBallList.get(key); //根据清单获得所需的球
if (playBall == null) { //清单上没有这种球
playBall = new PlayConcreteBall(); //虽然清单上没有这种球,但还想玩,那你先得到这种球,然后补清单
playBallList.put(key, playBall); //将这种球补写进清单
}
return playBall;
}
public Hashtable getPlayBallList() { //获得选球清单
return playBallList;
}
}
4、编写测试类:
public class Test {
public static void main(String args[]) {
Gymnasium gymnasium = new Gymnasium(); //我们去的体育馆
PlayBall badminton = gymnasium.getPlayBall( "羽毛球" ); //想得到羽毛球
PlayBall pingpangball = gymnasium.getPlayBall( "兵乓球" ); //想得到兵乓球
PlayBall vollyball = gymnasium.getPlayBall( "排球" ); //想得到排球
Hashtable selectedBallList = gymnasium.getPlayBallList(); //器材部得到选球清单
((PlayBall)selectedBallList.get("羽毛球")).playBall("羽毛球"); //得到羽毛球
((PlayBall)selectedBallList.get("兵乓球")).playBall("兵乓球"); //得到兵乓球
((PlayBall)selectedBallList.get("排球")).playBall("排球"); //得到排球
}
}