dimanche 20 décembre 2015

Factory class to handle logic of a constructor?

I have a Maze class which has a constructor:

public class Maze implements MazeInterface {

  private int width;          // Width of maze in units
  private int height;         // Height of maze in units
  private long seed;          // Seed generated for the maze
  private Cell[][] board;     // 2D representation of the maze

  public Maze(int w, int h, Cell[][] maze, long s){
      width = w;
      height = h;
      board = maze;
      seed = s;
  }

  // Bunch of other methods/stuff irrelevant

}

I was reading online about good practices and now I understand that a complex constructor is bad practice. So I thought a factory class would be a viable solution. What I want to do is generate a random seed, random w/h values for the maze (how many units wide or tall the maze is), and other logic for the Maze object. Is the factory pattern the right way to do this?

public class MazeFactory {

  public Maze createMaze(int w, int h){
      long s = generateSeed();       // Generation of a seed
      int w  = generateW();          // Random w value
      int h  = generateH();          // Random h value

      return new Maze(w, h, new Cell[w][h], s);
  }

  private long generateSeed(){
      // Do stuff and return a seed
  }

  private int generateW(){
      // Do stuff
  }

  private int generateH(){
      // Do stuff
  }

}

Would this separation of logic be beneficial by putting it into a Factory class or is this the wrong way to go about this (wrong pattern use/etc) or should I just do this within the Maze class in the constructor by writing private methods and calling them in the constructor? I am trying to learn about different patterns/best practices, but I think i'm misunderstanding the way Factory design is handled or if I am just using the wrong pattern.

Aucun commentaire:

Enregistrer un commentaire