Avoid instantiating a class in java

前端 未结 5 1698
死守一世寂寞
死守一世寂寞 2020-12-04 18:32

Recently I\'ve faced a question : How to avoid instantiating a Java class?

However, I answered by saying:

  1. If you don\'t want to instantiate

5条回答
  •  感情败类
    2020-12-04 18:48

    Four reasons spring to mind:

    1. To allow subclasses but not the parent to be instantiated;
    2. To disallow direct instantiation and instead provide a factory method to return and if necessary create instances;
    3. Because all the instances are predefined (eg suits in a deck of cards) although since Java 5, typesafe enums are recommended instead; and
    4. The class really isn't a class. It's just a holder for static constants and/or methods.

    As an example of (2), you may want to create canonical objects. For example, RGB color combinations. You don't want to create more than one instance of any RGB combo so you do this:

    public class MyColor {
      private final int red, green, blue;
    
      private MyColor(int red, int green, int blue) {
        this.red = red;
        this.green = green;
        this.blue = blue;
      }
    
      public static MyColor getInstance(int red, int green, int blue) {
        // if combo already exists, return it, otherwise create new instance
      }
    }
    

    Note: no no-arg constructor is required because another constructor is explicitly defined.

提交回复
热议问题