欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 结构型模式 - 享元模式 (Flyweight Pattern)

结构型模式 - 享元模式 (Flyweight Pattern)

2025/2/27 7:15:14 来源:https://blog.csdn.net/HongSH945/article/details/145846184  浏览:    关键词:结构型模式 - 享元模式 (Flyweight Pattern)

结构型模式 - 享元模式 (Flyweight Pattern)

享元模式是一种结构型设计模式,它通过共享对象来减少内存使用和提高性能,尤其适用于存在大量细粒度对象且这些对象有部分状态可共享的场景。


举个经典案例, 下围棋, 黑子和白子可以用享元,每一颗棋子除了放置的位置之外,只有颜色区分.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;// 享元接口,定义棋子的放置方法
interface ChessPieceFlyweight {String getColor();
}// 具体享元类,代表黑子和白子
class ConcreteChessPiece implements ChessPieceFlyweight {private String color;public ConcreteChessPiece(String color) {this.color = color;}@Overridepublic String getColor() {return color;}
}// 享元工厂类,负责创建和管理享元对象
class ChessPieceFactory {private static final Map<String, ChessPieceFlyweight> flyweights = new HashMap<>();public static ChessPieceFlyweight getChessPiece(String color) {ChessPieceFlyweight flyweight = flyweights.get(color);if (flyweight == null) {flyweight = new ConcreteChessPiece(color);flyweights.put(color, flyweight);}return flyweight;}
}// 表示棋盘上的位置
class Position {private int x;private int y;public Position(int x, int y) {this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}@Overridepublic String toString() {return "(" + x + ", " + y + ")";}
}// 记录棋子及其位置的类
class PlacedChessPiece {private ChessPieceFlyweight piece;private Position position;public PlacedChessPiece(ChessPieceFlyweight piece, Position position) {this.piece = piece;this.position = position;}public ChessPieceFlyweight getPiece() {return piece;}public Position getPosition() {return position;}@Overridepublic String toString() {return piece.getColor() + " 棋子放置在位置 " + position;}
}// 客户端代码
public class GoGameExample {public static void main(String[] args) {// 存储所有已放置的棋子List<PlacedChessPiece> placedPieces = new ArrayList<>();// 获取黑子和白子对象ChessPieceFlyweight blackPiece = ChessPieceFactory.getChessPiece("黑色");ChessPieceFlyweight whitePiece = ChessPieceFactory.getChessPiece("白色");// 放置黑子Position blackPos1 = new Position(1, 2);Position blackPos2 = new Position(3, 4);placedPieces.add(new PlacedChessPiece(blackPiece, blackPos1));placedPieces.add(new PlacedChessPiece(blackPiece, blackPos2));// 放置白子Position whitePos1 = new Position(2, 3);Position whitePos2 = new Position(4, 5);placedPieces.add(new PlacedChessPiece(whitePiece, whitePos1));placedPieces.add(new PlacedChessPiece(whitePiece, whitePos2));// 输出所有已放置的棋子及其位置for (PlacedChessPiece placedPiece : placedPieces) {System.out.println(placedPiece);}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词