简体   繁体   中英

What is the correct way to implement a Creator Class and the Class itself design in Java?

I am trying to decide on a design for all my classes and their creators.

For example I have 2 classes, Level and LevelLoader :

The design I have come so far is:

This is Level class:

public class Level implements Serializable {

    private byte[] map; 

    Level(LevelLoader loader){
        map = loader.getMap();
    }

    // ...
}

This is the Creator:

public interface LevelLoader {

    public Level loadLevel(InputStream stream);

    public byte[] getMap();
}

So for example to create a level instance in main file I'll write:

TextLoader is implementing LevelLoader interface above:

File file = new File("src/Level/level2.txt");
Level level1 = new Level(new TextLoader(file));

So I am curious what is the most logical way to connect them to the other?

certainly you will have more implementations in the near future. So without directly creating instances like TextLoader, get them using a Factory.

Sorry I quite not get what question is about?

perhaps: - you need to create many instances of your Level class during application run time - also you may need different kind of loaders (TextLoader, FileLoader, URLLoader and so on..)

Then you can create each loader once somewhere outside (ie Utiltiy or ObjectFactory class) and then reuse them to create instances.

something like that:

ObjectFactory class

private static LevelLoader filetLoaderInstance = new FileLoader("level2.txt");
private static LevelLoader urlLoaderInstance = new URLLoader("ftp://foo.com/level2.txt");

public static Level createLevelFromFile()
{
   return new Level(textLoaderInstance);
}

public static Level createLevelFromURL()
{
   return new Level(urlLoaderInstance);
}

In general without necessity of multiple usage such design is not needed. Like in your example with

Level level1 = new Level(new TextLoader(file));

It is quite overhead. What is the reason to have and create another object (TextLoader) if it will run only once?

But if that code has to run many times - it is not good. It is better to have only one instance of TextLoader rather than create it every time when instance of Loader class creates. It affects memory usage as well as performance of application.

What I feel is the below way.

InputStream is = new File("src/Level/level2.txt");
LevelLoader levelLoader = new TextLoader();
Level level = levelLoader.loadLevel(file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM