Home > Software engineering >  Conserving RAM in java by using references to objects
Conserving RAM in java by using references to objects

Time:12-06

I know some about java, and a lot about the lower level functions of a computer, so I'm always looking for ways to conserve ram. I'm also a fan of dwarf fortress, so I've been trying to get some similar system working. So, what I want to do is to make multiple tiles, assign them some type of material, and all the tiles with the same type of material share the same material object. I drew a little picture to illustrate it: here Does java do this automatically? or do I have to implement it by myself? If I make two copies of the material properties, is there a way to merge them both into one?

Thank you for responding.

CodePudding user response:

Lets say you have a material.

interface Material{
    void render( Context c);
}

Then you have some instance of the material.

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

In this case there would be 1 concrete texture for all of the instances of concrete, and it gets loaded when the class gets loaded. The texture gets assigned in the constructor, but you might use a factory method instead that would create new materials and load/assign the assets.

CodePudding user response:

I am not sure i understand your question, but lets say each tile is represented by an object and the material is represented by a shared object then you can use singleton pattern in 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();
    }
    
}
  • Related