设计模式-享元模式

享元模式

定义:使用共享物件,来减少内存使用量。通常物件中的部分状态时可以分享的,常见的做法时将他们放在外部数据结构中,当需要使用时再将它们传递给享元。能够避免重复创建。

应用实例:Java里的String字符串缓存池。数据库的数据池

使用场景:系统里有大量相似对象,需要用到缓存的场景

需要注意线程安全问题。

结构:

  • Flyweight 抽象享元角色
  • ConcreteFlyweight 具体享元角色
  • UnsharedConcreteFlyweight 非享元角色
  • FlyweightFactory 享元工厂角色

客户角色可以通过享元工厂去获取具体的享元对象,并调用相关方法。

示例场景:五子棋中的应用。我们都知道五子棋中包含了大量的“黑棋”和“白棋”,而这些棋子是可以复用的,而下棋的坐标是每次都不一样,属于非享元角色。

代码示例:

public interface ChessPieces {

    void downPieces(PiecePoint piecePoint);
}
public class ConcreteChessPieces implements ChessPieces {

    private String color;

    public ConcreteChessPieces(String color) {
        this.color = color;
    }

    @Override
    public void downPieces(PiecePoint piecePoint) {
        System.out.println(color+"棋,下在了坐标"+piecePoint.getX()+","+piecePoint.getY());
    }
}

public class PiecePoint {

    private int x;
    private int y;

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

    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 class ChessPiecesFactory {


    private static final HashMap<String,ChessPieces> chessPiecesHashMap=new HashMap<>();

    public static ChessPieces getChessPiecesHashMap(String color) {
        if("白".equals(color)||"黑".equals(color)){
            ChessPieces chessPieces = chessPiecesHashMap.get(color);
            if(chessPieces!=null){
                return chessPieces;
            }
            ChessPieces newChessPieces=new ConcreteChessPieces(color);
            chessPiecesHashMap.put(color,newChessPieces);
            return newChessPieces;
        }
        return null;
    }
}

测试:

   public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {
        ChessPieces whiteChessPieces = ChessPiecesFactory.getChessPiecesHashMap("白");
        whiteChessPieces.downPieces(new PiecePoint(1,2));

        ChessPieces blackChessPieces = ChessPiecesFactory.getChessPiecesHashMap("黑");
        blackChessPieces.downPieces(new PiecePoint(2,4));

        whiteChessPieces.downPieces(new PiecePoint(3,9));
        blackChessPieces.downPieces(new PiecePoint(7,4));

    }

返回目录

posted @ 2021-06-28 21:43  女友在高考  阅读(53)  评论(0编辑  收藏  举报