Factory pattern or builder pattern? Not sure what to google

I am not sure what I need to google here.
Lets say I have a class like this

1
2
3
4
5
6
7
8
9
Class monster
{
public:
  ~monster();
private: // private constructors
  monster();
  monster(int hp, int mp) { m_hp = hp; m_mp = mp;};
  int m_hp, m_mp
};


Now I want to to have a txt file like

1
2
3
Orc, 100,0
Elf,50,100
Generic_Tolkienoid 100,100


I want to have another class (which is a friend of monster class) which reads the txt file and makes these objects and puts them in a std::unordered_map, using the name as a key. Which design pattern is this, factory, builder, something else?

Also are there any better ways of doing this?
Since monster is not a polymorphic type, a simple function would do the job.

Something along these lines:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class monster
{
    public:
        static std::unordered_map< std::string, monster > get_instances( std::istream& stm ) ;

    private: // private constructors
      monster();
      monster(int hp, int mp) { m_hp = hp; m_mp = mp;};
      int m_hp, m_mp ;
};

std::unordered_map< std::string, monster > monster::get_instances( std::istream& stm )
{
    std::unordered_map< std::string, monster > monsters ;

    std::string name ;
    int hp, mp ;
    char sep ;
    const char comma = ',' ;

    while( std::getline( stm, name, ',' ) && stm >> hp >> sep >> mp && sep == comma && stm.ignore( 1000, '\n' ) )
    {
        // sanitise name if required (remove leading/trailing white-space etc.)
        monsters.insert( { name, {hp,mp} } ) ;
    }

    return monsters ;
}

http://coliru.stacked-crooked.com/a/c47b434ebd91cdf6
Thanks that is cool, I guess by using std::istream the monster class doesn't care if the stream is a file stream or string stream.

I suppose if you used a filestream and loaded the file in the monster class that would work to, but then the class then wouldn't "Do one thing" anymore.
Topic archived. No new replies allowed.