小工具知识网

当前位置: 首页 > 行业知识 > 设计模式-享元模式实践案例

行业知识

设计模式-享元模式实践案例

2026-11-12 13:50:43 来源:互联网转载

享元���式(Flyweight Pattern)是一种结构型设计模式,其核心思想是通过共享技术来有效地支持大量细粒度对象的复用,减少创建对象的数量,以节省系统资源,特别是内存。

()

以下是一个使用 Java 实现享元模式的实践案例:

场景描述

假设我们正在开发一个文本编辑器,需要处理大量的字符对象。每个字符都有自己的样式属性,如字体、大小、颜色等。为了避免为文档中的每个字符创建大量对象,我们可以使用享元模式来重用相同样式的字符对象。

()

步骤1:创建享元接口

1// 字符享元接口2public interface CharacterFlyweight {3    void display();4}

步骤2:实现具体的享元类

1// 具体的字符享元类2public class ConcreteCharacterFlyweight implements CharacterFlyweight {3    private char character;4    private String style; // 字体样式,例如字体大小,颜色等56    public ConcreteCharacterFlyweight(char character, String style) {7        this.character = character;8        this.style = style;9    }1011    @Override12    public void display() {13        System.out.println("Character: " + character + " with Style: " + style);14    }15}

步骤3:创建享元工厂类

享元工厂类用于创建和管理享元对象,确保相同的享元只被创建一次。

1import java.util.HashMap;2import java.util.Map;34// 享元工厂类5public class FlyweightFactory {6    private Map flyweights = new HashMap();78    public CharacterFlyweight getFlyweight(char character, String style) {9        String key = character + "-" + style;10        if (!flyweights.containsKey(key)) {11            flyweights.put(key, new ConcreteCharacterFlyweight(character, style));12        }13        return flyweights.get(key);14    }15}

步骤4:客户端代码使用享元模式

1public class FlyweightPatternDemo {2    public static void main(String[] args) {3        FlyweightFactory factory = new FlyweightFactory();4        String style = "Font: Arial, Size: 12, Color: Black";56        CharacterFlyweight charA = factory.getFlyweight('A', style);7        charA.display();89        CharacterFlyweight charB = factory.getFlyweight('B', style);10        charB.display();1112        // 由于样式相同,这里的 charA2 会重用之前创建的 'A' 字符对象13        CharacterFlyweight charA2 = factory.getFlyweight('A', style);14        charA2.display();1516        // 验证两个 'A' 字符是否是相同的实例17        System.out.println("charA == charA2: " + (charA == charA2));18    }19}

在上述代码中,

ConcreteCharacterFlyweight 是具体的享元类,表示具有特定样式的字符。FlyweightFactory 负责管理享元对象的缓存,getFlyweight 方法确保不会为相同的字符和样式创建多个对象。

客户端代码通过享元工厂来获取享元对象。如果请求了具有相同样式的相同字符,则工厂会返回之前创建的相同对象的引用,而不是创建新对象;这样可以减少实例的数量,节省内存。

享元模式在处理大量类似对象时非常有用,可以显著减少内存消耗。这种模式在图形处理、游戏开发和文本处理等领域中广泛应用。

上一篇:Facebook海外户&Facebook广告被暂停的原因

下一篇:JavaScript实现加法按钮计算详解