编程-设计模式 11:享元模式

设计模式 11:享元模式

定义与目的
  • 定义:享元模式运用共享技术有效地支持大量细粒度的对象。它通过共享已经创建的对象来减少需要创建的新对象的数量,从而减少内存占用和提高性能。
  • 目的:该模式的主要目的是减少创建大量相似对象所需的内存消耗,特别是在需要大量实例时。
实现示例

假设我们需要在一个游戏中创建大量的棋子对象,这些棋子只有颜色和位置的区别。我们可以使用享元模式来减少内存消耗。

java 复制代码
// 享元接口
interface ChessPiece {
    void setPosition(int x, int y);
    void display();
}

// 具体享元 - 棋子
class ChessPieceImpl implements ChessPiece {
    private final String color;
    private int x, y;

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

    @Override
    public void setPosition(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void display() {
        System.out.println("Chess piece of color " + color + " at (" + x + "," + y + ")");
    }
}

// 享元工厂
class ChessPieceFactory {
    private Map<String, ChessPiece> pool = new HashMap<>();

    public ChessPiece getChessPiece(String color) {
        ChessPiece chessPiece = pool.get(color);
        if (chessPiece == null) {
            chessPiece = new ChessPieceImpl(color);
            pool.put(color, chessPiece);
            System.out.println("Created new chess piece of color " + color);
        }
        return chessPiece;
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        ChessPieceFactory factory = new ChessPieceFactory();

        ChessPiece blackPiece = factory.getChessPiece("black");
        blackPiece.setPosition(0, 0);
        blackPiece.display();  // 输出: Created new chess piece of color black
                               //       Chess piece of color black at (0,0)

        ChessPiece whitePiece = factory.getChessPiece("white");
        whitePiece.setPosition(1, 1);
        whitePiece.display();  // 输出: Created new chess piece of color white
                               //       Chess piece of color white at (1,1)

        ChessPiece anotherBlackPiece = factory.getChessPiece("black");
        anotherBlackPiece.setPosition(2, 2);
        anotherBlackPiece.display();  // 输出: Chess piece of color black at (2,2)
    }
}
使用场景
  • 当你需要创建大量的相似对象时。
  • 当对象的大部分状态可以外部化时(即可以通过参数传递给对象的方法来设置)。
  • 当你希望减少内存消耗时。

享元模式通过共享对象来减少内存消耗,特别是在需要创建大量相似对象时。它适用于那些对象的内部状态可以被外部化的场景。

小结

享元模式是一种常用的结构型模式,它有助于减少内存消耗,特别是在需要创建大量相似对象时。这对于提高系统的性能和资源利用率非常有益。

相关推荐
cfm_291432 分钟前
Leaf-segment号段模式
java
Wang's Blog34 分钟前
Java 项目实战: 交友项目 - 发布圈子动态:数据库表和接口文档介绍
java·数据库·交友
是2的10次方啊35 分钟前
设计模式与生活①:你的脸,为什么不能有第二个?
设计模式
paopaokaka_luck35 分钟前
智慧电玩店管理系统(空闲机台随机分配、游玩时长概率模拟、积分自动结算、积分兑换闭环、 ECharts经营分析、 腾讯地图选址)
java·人工智能·mysql·echarts·推荐算法
LMT流氓兔1 小时前
第五单元——第9课:防止同一次操作重复执行
java·服务器·数据库·算法·ai·langchain
OxYGC1 小时前
Spring 面经系列 · 第 6 篇:Spring MVC 请求全流程、父子容器与零配置原理
java·spring·mvc
code2cat1 小时前
Java高级篇之JDBC:连接数据库,完成查询、更新与事务
java·开发语言·数据库
bksczm1 小时前
Redis数据结构之string
java·redis·mybatis
cc_瀚海知行1 小时前
资料检索 1|直接放入全文、按需读文件和先检索,有什么区别?
java·人工智能·ai
BioRunYiXue2 小时前
使用docker分析高通量测序数据
java·数据库·人工智能·spring cloud·docker·tomcat·html