Static Factory Method

Pros

  • By using a static factory method you remove the creation logic outside of the class
  • Creating objects, like in the example, can increase readability. For example Sword.weakerThan(50) is easier to understand than new Sword(1, 50);

Cons

  • Can't instantiate a subclass from a private constructor using a static factory method

Example Explanation

Static methods (weakerThan, between, strongerThan) - Al

import java.util.Random;
class Main {
  public static void main(String[] args) {
    Sword s1 = Sword.weakerThan(50);
    Sword s2 = Sword.between(200, 300);
    Sword s3 = Sword.strongerThan(500);
  }
}

class Sword{
  private int attack;
  private Sword(int minAttack, int maxAttack){
    Random r = new Random();

    this.attack = r.nextInt((maxAttack - minAttack) + 1) + minAttack;;

    System.out.println("Sword: [ATK: "+attack+"]");
  }

  public static Sword weakerThan(int maxAttack){
    return new Sword(1, maxAttack);
  }
  public static Sword between(int minAttack, int maxAttack){
    return new Sword(minAttack, maxAttack);
  }
  public static Sword strongerThan(int minAttack){
    return new Sword(minAttack, 1000);
  }
}

Extra Resources

Constructors or Static Factory Methods?

results matching ""

    No results matching ""