首页 > 图灵资讯 > 技术篇>正文

蝇量级

2024-09-18 15:18:12

蝇量级

其中一种结构模式旨在通过与相似对象共享尽可能多的数据来减少内存使用。 它在处理大量相似物体时特别有用,因为为每个物体创建一个新的例子在内存消耗方面非常昂贵。 关键概念: 内部状态:多个对象之间的共享状态独立于上下文,并在不同对象之间保持相同。 外部状态:从客户端传递给每个对象的唯一状态。这种状态可能不同,不存储 flyweight 对象中

主要参与者:

flyweight:flyweight 对象接收外部状态并使用其接口。 concreteflyweight:实现 flyweight 并存储内部状态。 flyweightfactory:管理flyweight对象,确保界面共享,如果存在,返回现有flyweight。

client(如 main 类):维护对 flyweight 引用,需要和 flyweight 当对象交互时,提供外部状态。

让我们举一个角色享元对象的例子 假设我们有一个需要渲染大量文本的文本编辑器。每个字符都可以表示为一个对象,但每个字符都有一个单独的对象,这将浪费大量内存。相反,我们可以使用它 flyweights 共享代表每个字母的字符对象,并存储外部状态,如外部位置或格式

蝇量级

public interface flyweight {
    public void display(int x, int y);//x, y are the extrinsic state of the flyweight object
}

混凝土苍蝇量级

public class characterflyweight implements flyweight {
    private char ch;
    public characterflyweight(char c){
        this.ch  = c;
    }
    @override
    public void display(int x ,int y){
        system.out.println("[drawing character: "+this.ch+" at co-ordinates:("+x+","+y+")]");
    }

}

flyweightfactory

public class flyweightfactory {
    private static hashmap<character> flyweights = new hashmap();
    public static flyweight getflyweight(char c){
        flyweight flyweight = flyweights.getordefault(c,null);
        if(null==flyweight){
            flyweight = new characterflyweight(c);
            flyweights.put(c,flyweight);
        }
        return flyweight;
    }
}
</character>

主要

public class main {
    public static void main(string args[]){
        flyweight flyweight1 = flyweightfactory.getflyweight('a');
        flyweight flyweight2 = flyweightfactory.getflyweight('b');
        flyweight flyweight3 = flyweightfactory.getflyweight('a');// will use the same object that is referenced by flyweight1

        flyweight1.display(1, 2);//'a' displayed at 1,2
        flyweight2.display(3, 4);//'b' displayed at 3,4
        flyweight3.display(5, 7); // 'a'(shared) displayed at 5,7
    }
}

输出:

[drawing character: a at co-ordinates:(1,2)]
[drawing character: b at co-ordinates:(3,4)]
[drawing character: a at co-ordinates:(5,7)]

要点

  • 内存效率:通过共享对象来减少内存的使用,特别是当内部状态较大或对象较多时。
  • 性能改进:在管理大量对象时,减少创建对象的数量可以提高应用程序的性能。

缺点复杂性:这种模式会增加代码的复杂性,特别是在分别管理外部和内部状态时。开销:如果共享的对象很少,享元模式可能会引入不必要的复杂性,而不会显著节省内存。

以上是飞量级的详细内容。请关注图灵教育的其他相关文章!

上一篇 Java 混淆之谜
下一篇 返回列表

文章素材均来源于网络,如有侵权,请联系管理员删除。