When to use a Constructor and when to use getInstance() method (static factory methods)?

前端 未结 6 869
孤城傲影
孤城傲影 2020-11-27 10:45
  1. When and how should we use a constructor

    Foo bar = new Foo();
    
  2. And when and how should we use getInstance() (static factory

6条回答
  •  借酒劲吻你
    2020-11-27 11:03

    The uses for getInstance methods:

    • If you want to control/restrict construction e.g. Singleton
    • implement Factory pattern, e.g. DriverManager.getConnection
    • When you want to provide better name as to how the instance is constructed (constructors must have the same name as the class name), checkout the NumberFormat factory methods getCurrencyInstance, getIntegerInstance and others as examples of this.

    But most of the time your object will be a simple POJO and usage of public constructors is most practical and obvious solution.

    U1: getInstance From Another Class

    To return an instance of a different class:

    public class FooFactory {
        public static Foo getInstance() {
            return new Foo();
        }
    }
    

    NumberFormat.getInstance methods do this as they actually return instances of DecimalFormat.

    U2: Singleton Problems

    The singleton pattern restricts many of the benefits of object oriented programming. Singletons generally have private constructors, therefore you cannot extend them. As you will be accessing it via its getInstance method and not referencing any interface, you will not be able to swap it out for another implementation.

提交回复
热议问题