【问题标题】:Conserving RAM in java by using references to objects通过使用对对象的引用来节省 Java 中的 RAM
【发布时间】:2022-01-11 05:23:00
【问题描述】:

我对 java 有一些了解,对计算机的底层功能也有很多了解,所以我一直在寻找节省 ram 的方法。我也是矮人要塞的粉丝,所以我一直在尝试让一些类似的系统工作。所以,我想做的是制作多个瓦片,为它们分配某种类型的材质,所有具有相同类型材质的瓦片共享同一个材质对象。我画了一张小图来说明:here java会自动执行此操作吗?还是我必须自己实施?如果我制作了两个材料属性的副本,有没有办法将它们合并为一个?

感谢您的回复。

【问题讨论】:

  • "java 会自动执行此操作吗?" 否。对象池模式。
  • 您能否澄清一下“对象池模式”是什么?或如何实施?我在网上看了一下,很多网站只在新对象“创建成本高”时才谈论使用它。他们都没有真正谈论使用它来节省内存。我应该在谷歌上搜索它还有其他名称吗?
  • 您不一定需要对象池。您可以将数据设为静态,因此它将与类相关联。然后材质的新实例都将引用同一个对象。不过你的问题有点含糊。

标签: java memory


【解决方案1】:

假设你有一个材料。

interface Material{
    void render( Context c);
}

那么你有一些材料的实例。

class Concrete implements Material{
    static Texture concreteTexture = loadConcreteTexture();
    Texture texture;
    public Concrete(){
      texture = concreteTexture();
    }
    void render(Context c){
        //do stuff with texture.
    }
}

在这种情况下,所有混凝土实例都会有 1 个混凝土纹理,并且在加载类时加载它。纹理在构造函数中分配,但您可以使用工厂方法来创建新材质并加载/分配资产。

【讨论】:

    【解决方案2】:

    我不确定我是否理解你的问题,但是假设每个图块都由一个对象表示,而材质由一个共享对象表示,那么您可以在 java 中使用单例模式:

    interface MatType{
        String getType();
        void draw();
    }
    
    class Cement implements MatType{
        private static Cement cement = null;
        
        private string type = "Cement";
    
        /*some cement properties here*/
    
        private Cement(){}
    
        /*
    By using this method you will get always the same
            object which will be shared between all objects
            that reference it.
        */ 
        public static Cement getInstance(){
                if (cement == null)
                    cement = new Cement();
                return cement;
        }
        
        String getType(){
            return type;
        }
        
        void draw(){
        //draw
        }
        
    }
    
    class Tile{
        MatType type = null;
        
        /*tile properties*/
        
        public Tile(String t){
            if (t.equals("Cement"))
                type = (MatType)Cement.getInstance(); /*casting is for clarification only*/
            if (t.equals("Iron"))
                type = Iron.getInstance(); /*same logic of Cement*/
            .
            .
            .
        }
        
        String getType(){
            return type.getType();
        }
        
        void draw(){
            type.draw();
        }
        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-04
      • 2016-11-28
      • 2011-12-12
      • 2011-12-29
      • 2011-08-28
      • 2020-09-01
      相关资源
      最近更新 更多