享元模式--Java实现
画类图
在围棋中,黑棋和白棋对象均只有一个,但是它们可以在不同的位置进行共享;
具体代码实现
//Chess.java
package org.example.design010;
public abstract class Chess {
public abstract String getColor();
public void locate(Coordinates co){
System.out.println(this.getColor()+"棋的位置是:("+co.getX()+","+co.getY()+")");
}
}
//WhiteChess.java
package org.example.design010;
public class WhiteChess extends Chess{
@Override
public String getColor() {
return "白";
}
}
//BlackChess.java
package org.example.design010;
public class BlackChess extends Chess{
@Override
public String getColor() {
return "黑";
}
}
//Coordinates.java
package org.example.design010;
public class Coordinates {
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
}
//ChessFactory.java
package org.example.design010;
import java.util.Hashtable;
public class ChessFactory {
public static ChessFactory getChessFactory() {
return chessFactory;
}
private static Hashtable hashTable;
public ChessFactory(){
hashTable=new Hashtable();
Chess black,white;
black=new BlackChess();
hashTable.put("b", black);
white=new WhiteChess();
hashTable.put("w",white);
}
public static ChessFactory getInstance() {
return chessFactory;
}
private static ChessFactory chessFactory=new ChessFactory();
public static Chess getChess(String color){
return (Chess) hashTable.get(color);
}
}
//Client.java
package org.example.design010;
public class Client {
public static void main(String[] args) {
Chess black1,black2,black3,white1,white2;
ChessFactory factory;
factory=ChessFactory.getInstance();
black1=ChessFactory.getChess("b");
black2=ChessFactory.getChess("b");
black3=ChessFactory.getChess("b");
white1=ChessFactory.getChess("w");
white2=ChessFactory.getChess("w");
black1.locate(new Coordinates(1,2));
black2.locate(new Coordinates(2,3));
black3.locate(new Coordinates(3,4));
white1.locate(new Coordinates(4,5));
white2.locate(new Coordinates(5,6));
}
}