蝇量级

蝇量级

其中一种结构模式旨在通过与相似对象共享尽可能多的数据来减少内存使用。
在处理大量相似对象时特别有用,因为为每个对象创建一个新实例在内存消耗方面会非常昂贵。
关键概念:
内在状态:多个对象之间共享的状态独立于上下文,并且在不同对象之间保持相同。
外部状态:每个对象唯一的、从客户端传递的状态。此状态可能会有所不同,并且不会存储在 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)]

要点

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

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

以上就是蝇量级的详细内容,更多请关注www.sxiaw.com其它相关文章!