[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
类图
代码
java代码
package test13;
public class BlackChess implements Chess{
private String color = "黑色";
@Override
public String getColor() {
return color;
}
@Override
public void location(Location location) {
}
}
package test13;
public interface Chess {
public String getColor();
public void location(Location location);
}
package test13;
import java.util.ArrayList;
public class ChessFactory {
private ArrayList chess = new ArrayList();
//单例模式
private static ChessFactory chessFactory = null;
private ChessFactory(){
}
//简单工厂模式
public Chess productChess(String type) throws Exception {
if(type.equalsIgnoreCase("hz")){
System.out.println("棋子工厂生产黑子");
BlackChess hz = new BlackChess();
chess.add(hz);
return hz;
}else if(type.equalsIgnoreCase("bz")){
System.out.println("棋子工厂生产白子");
WhiteChess bz = new WhiteChess();
return bz;
}else {
throw new Exception("对不起,没有该颜色的棋子");
}
}
//单例模式
public static ChessFactory getInstance(){
if(chessFactory==null){
chessFactory = new ChessFactory();
}else {
System.out.println("重复生成工厂");
}
return chessFactory;
}
public int getChessNum(){
return chess.size();
}
public ArrayList getChess() {
return chess;
}
public void setChess(ArrayList chess) {
this.chess = chess;
}
}
package test13;
public class Client {
public static void main(String[] args) throws Exception {
Chess c1,c2,c3,c4;
ChessFactory cf;
cf = ChessFactory.getInstance();
c1 = cf.productChess("hz");
c1.location(new Location("1,1"));
c2 = cf.productChess("bz");
c2.location(new Location("2,1"));
c3 = cf.productChess("hz");
c3.location(new Location("3,1"));
c4 = cf.productChess("bz");
c4.location(new Location("4,1"));
}
}
package test13;
public class Location {
private String location;
public Location(String location){
this.location = location;
System.out.println("棋子位置为"+location);
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
}
package test13;
public class WhiteChess implements Chess {
private String color = "白色";
@Override
public String getColor() {
return color;
}
@Override
public void location(Location location) {
}
}
标签:享元,13,return,String,模式,location,new,public,Location
From: https://www.cnblogs.com/java-six/p/16789306.html