通俗易懂的Java设计模式之 --享元模式

Java中的享元模式(Flyweight Pattern)是一种结构型设计模式,它旨在通过共享对象来减少内存和对象创建的开销。享元模式适用于有大量相似对象的情况,其中大部分对象的状态可以被共享而不需要单独存储。

下面是一个简单的Java代码示例,演示了如何使用享元模式来减少内存和对象创建的开销。假设我们有一个游戏中的棋盘类ChessBoard,其中包含了很多棋子ChessPiece对象。每个棋子对象包含了颜色和形状两个属性:

public class ChessPiece {
    private ChessPieceColor color;
    private String shape;

    public ChessPiece(ChessPieceColor color, String shape) {
        this.color = color;
        this.shape = shape;
    }

    public ChessPieceColor getColor() {
        return color;
    }

    public String getShape() {
        return shape;
    }
}

现在,假设我们需要在棋盘上绘制很多相同颜色和形状的棋子。如果每个棋子都创建一个新的对象,将会占用大量的内存和增加对象创建的开销。我们可以使用享元模式来解决这个问题。

public class ChessPieceFactory {
   private static final Map<ChessPieceColor, ChessPiece> chessPieces = new HashMap<>();

    public static ChessPiece getChessPiece(ChessPieceColor color) {
        ChessPiece chessPiece = chessPieces.get(color);
        if (chessPiece == null) {
            chessPiece = new ChessPiece(color, "pawn");
            chessPieces.put(color, chessPiece);
        }
        return chessPiece;
    }
}

在上述代码中,我们创建了一个ChessPieceFactory类,它包含了一个静态的Map对象,用于存储已创建的棋子对象。在getChessPiece方法中,我们首先尝试从Map中获取指定颜色的棋子对象,如果找不到,则创建一个新的棋子对象,并将其存储在Map中以便下次使用。

现在,客户端可以使用ChessPieceFactory类来获取棋子对象,而不是直接创建新的对象:

public class Client {
    public static void main(String[] args) {
       ChessPiece whitePawn1 = ChessPieceFactory.getChessPiece(ChessPieceColor.WHITE);
       ChessPiece whitePawn2 = ChessPieceFactory.getChessPiece(ChessPieceColor.WHITE);
       ChessPiece blackPawn1 = ChessPieceFactory.getChessPiece(ChessPieceColor.BLACK);
       ChessPiece blackPawn2 = ChessPieceFactory.getChessPiece(ChessPieceColor.BLACK);

        System.out.println(whitePawn1 == whitePawn2); // true,表示两个对象是同一个
        System.out.println(blackPawn1 == blackPawn2); // true,表示两个对象是同一个
    }
}

在上述代码中,我们创建了四个棋子对象,并使用ChessPieceFactory类来获取它们。由于白色棋子和黑色棋子都是相同的颜色和形状,因此它们将共享同一个棋子对象,而不是每个棋子都创建一个新的对象。这样可以大大减少内存的使用和对象创建的开销。

需要注意的是,享元模式并不总是适用于所有情况。如果对象的状态变化频繁,那么共享对象可能会导致意想不到的行为。因此,需要仔细评估对象的使用场景,并在必要时使用享元模式。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值