是随外部环境随时会变化的部分,由客户端通过参数的形式传入。
public abstract class AbstractChess {
//棋子位置,外蕴状态,不可以共享
protected int x;
protected int y;
//棋子类别,内蕴状态,可以共享
protected String chess;
public AbstractChess(String chess) {
this.chess = chess;
}
public void point(int x,int y){
this.x = x;
this.y = y;
this.show();
}
public void show(){
System.out.println(this.chess+"("+this.x+","+this.y+")");
}
}
public class BlackChess extends AbstractChess {
public BlackChess() {
super("●");
System.out.println("BlackChess Constructor Used!!");
}
}
public class WhiteChess extends AbstractChess {
public WhiteChess() {
super("○");
System.out.println("WhiteChess Constructor Used!!");
}
}
获取棋子的工厂
public class ChessFactory {
private static ChessFactory chessFactory = new ChessFactory();
private ChessFactory() {
}
public static ChessFactory getFactoryInstance(){
return chessFactory;
}
private final Hashtable<Character, AbstractChess> chache = new Hashtable<Character, AbstractChess>();
/**
* 缓存中有则直接拿出,没有则先新建,放入,返回,返回后的棋子可以改变其外蕴状态
*/
public AbstractChess getChessObject(Character c){
AbstractChess abChess = chache.get(c);
if(abChess == null){
switch (c) {
case 'B':
abChess = new BlackChess();
break;
case 'W':
abChess = new WhiteChess();
break;
default:
break;
}
if(abChess != null){
chache.put(c, abChess);
}
}
return abChess;
}
}
测试
public class Client {
public static void main(String[] args) {
ChessFactory cFactory = ChessFactory.getFactoryInstance();
AbstractChess abstractChess = null;
Random random = new Random();
int radom = 0;
for (int i = 0; i < 10; i++) {
radom = random.nextInt(2);
switch (radom) {
case 0:
abstractChess = cFactory.getChessObject('B');
break;
case 1:
abstractChess = cFactory.getChessObject('W');
break;
default:
break;
}
if(abstractChess != null){
abstractChess.point(i, random.nextInt(15));
// abstractChess.show();
}
}
}
}