简体   繁体   中英

Java object construction by factory method: attribute vs constructor (via method)

I have a class (A) that uses (1) another class (B) by factory method (2):

(A)
public class MazeGame{
  private Room room;  // (1)

  public MazeGame() {
    this.room= makeRoom();   // (2)
  }

  protected Room makeRoom() {
    return new OrdinaryRoom();
  }
}

for example:

(B)
public class OrdinaryRoom{
  private String name = "ordinaryRoom";
}

I can also write (A) as:

(A2)
public class MazeGame{
  private Room room = makeRoom();  // (1)(2)

  protected Room makeRoom(){
    return new OrdinaryRoom();
  }
}

What's the difference between (A) and (A2)? there's some advantage by using one instead the other?

The differences I see:

  • A tiny difference in the moment of initializing room : With (A), it's initialized after finishing the super constructor Object() call, inside the MazeGame() constructor. With (A2) the initializing takes place after finishing the super constructor Object() call and before the first line of any MazeGame(...) constructor. In your case, it doesn't make a difference.
  • The initialization from (A2) applies to all constructors that MazeGame will ever have, while the (A) approach only initializes room in this single MazeGame() constructor , not affecting any constructors you might add in the future.
  • Moving the initialization to the room field "allowed" you to remove the constructor from your source code and to rely on the default constructor that the compiler generates in case there is no constructor. I don't see that as a benefit, but as a maintenance risk, because if in the future you want to add some eg MazeGame(Room room) constructor, this not only adds the new constructor (the expected result), but also removes the default one - might be quite unexpected.

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