设计模式之享元模式

概念:是池技术的重要实现方式,可以降低大量重复的、细粒度的类在内存中的开销。

享元模式是以共享的方式高效地支持大量的细粒度对象。

享元对象能做到共享的关键是区分内部状态和外部状态。

  • 内部状态是存储在享元对象内部、可以共享的信息,并且不会随环境改变而改变。
  • 外部状态是随环境改变而改变并且不可以共享的状态。在需要使用的时候从外部传入享元对象内部。
  • 抽象享元,定义需要的操作。
  • 具体享元类,一般可以分为内部状态和外部状态。
  • 享元工厂,维护一个享元对象的池子,用到对象的时候取出来。

用一个下围棋的例子来帮助大家理解。围棋只有黑棋和白棋,不必每次都创建新对象,这是内部状态。而棋子的落点可以作为外部状态传进来。

java 复制代码
public abstract class Flyweight {
    void put(Flyweight position) {
    }
    int getX() {
        return 0;
    }
    int getY() {
        return 0;
    }
}

public class ChessFlyweight extends Flyweight {
    private String color;
    public ChessFlyweight(String color) {
        this.color = color;
    }
    @Override
    public void put(Flyweight position) {
        if (!(position instanceof PositionFlyweight)) {
            System.out.println("位置错误。");;
        }
        System.out.println("在位置:" + "("+ position.getX() + "," + position.getY() +"), 放置了" + color + "棋子");
    }
}

public class PositionFlyweight extends Flyweight {
    private final int x;
    private final int y;
    public PositionFlyweight(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public int getX() {
        return x;
    }
    @Override
    public int getY() {
        return y;
    }
}

public class FlyweightFactory {
    private static final Flyweight WHITE = new ChessFlyweight("白色");
    private static final Flyweight BLACK = new ChessFlyweight("黑色");
    public static Flyweight getChess(String color) {
        if (color.equals("白色")) {
            return WHITE;
        } else if (color.equals("黑色")) {
            return BLACK;
        }
        return null;
    }
}

public class Demo {
    public static void main(String[] args) {
        Flyweight whiteChess1 = FlyweightFactory.getChess("黑色");
        Flyweight whiteChess2 = FlyweightFactory.getChess("黑色");
        Flyweight blackChess1 = FlyweightFactory.getChess("白色");
        Flyweight blackChess2 = FlyweightFactory.getChess("白色");
        whiteChess1.put(new PositionFlyweight(1, 1));
        blackChess1.put(new PositionFlyweight(2, 2));
        whiteChess2.put(new PositionFlyweight(3, 3));
        blackChess2.put(new PositionFlyweight(4, 4));
    }
}

如果大家需要视频版本的讲解,欢迎关注我的B站。

十三、设计模式之享元模式讲解

相关推荐
饮水桶_T12 小时前
Java调用大语言模型 笔记
笔记·设计模式·电脑·ai编程
ssshooter1 天前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式
饮水桶_T2 天前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AI酒旅实战开发3 天前
旅行 AI Agent 的 7 种设计模式:从工具调用到交易闭环
人工智能·设计模式
geovindu4 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu6 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh10 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊11 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua33311 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx12 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent