享元模式--Java实现

相关类图

具体代码

//ChessFactory.java
package org.example.test012;

import java.util.Hashtable;

public class ChessFactory {
    public static ChessFactory getChessFactory() {
        return chessFactory;
    }

    public static ChessFactory chessFactory = new ChessFactory();
    public static Hashtable ht;

    public ChessFactory() {
        ht = new Hashtable();
        Chess black, white;
        black = new BlackChess();
        ht.put("b", black);
        white = new WhiteChess();
        ht.put("w", white);
    }

    public static Chess getChess(String color) {
        return (Chess)ht.get(color);
    }


}

//Coordinates.java
package org.example.test012;

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;
    }

    private int x;
    private int y;

    public Coordinates(int x, int y) {
        this.x = x;
        this.y = y;
    }

}

//Chess.java
package org.example.test012;

public abstract class Chess {
    public abstract String getColor();
    public void getLocate(Coordinates co) {
        System.out.println(this.getColor() + "棋的位置为:(" + co.getX() + ", " + co.getY() + ")");
    }
}

//WhiteChess.java
package org.example.test012;

public class WhiteChess extends Chess {
    @Override
        public String getColor() {
        return "白";
    }
}

//BlackChess.java
package org.example.test012;

public class BlackChess extends Chess {
    @Override
        public String getColor() {
        return "黑";
    }
}

//Client.java
package org.example.test012;

public class Client {
    public static void main(String[] args) {
        Chess black1, black2, black3, white1, white2;
        ChessFactory chessFactory;
        chessFactory = ChessFactory.getChessFactory();
        black1 = chessFactory.getChess("b");
        black2 = chessFactory.getChess("b");
        black3 = chessFactory.getChess("b");
        white1 = chessFactory.getChess("w");
        white2 = chessFactory.getChess("w");

        black1.getLocate(new Coordinates(1, 1));
        black2.getLocate(new Coordinates(2, 4));
        black3.getLocate(new Coordinates(4, 1));
        white1.getLocate(new Coordinates(2, 6));
        white2.getLocate(new Coordinates(8, 0));

    }
}

运行结果

posted @ 2023-11-13 08:44  yesyes1  阅读(8)  评论(0编辑  收藏  举报