Consider providing static factory methods instead of constructors

The usual way for a class to allow a client to get an instance is to provide a public constructor. Another way to do this is to provide a public static factory method, which is just a static method that returns an instance of the class. What are the pros and cons of using a static factory method?

+2
source share
5 answers

This chapter in Effective Java explains this well: Consider Static Factory instead of constructors . He explains all the pros and cons for both of them in the best way, as you can understand.

Just to quote the advantages and disadvantages from the book:

< > :

  • Factory , .
  • Factory , theyre.
  • Factory , , , .
  • Factory , ( Java 7)

  • Factory ,

  • Factory , .

, .

+9

con - , , factory.

Factory , .

Factory , , .

, . factory, , new, , .

+2

: - factory , , , . factory , , , . - . Disavantage: factory , . - .

+1

, factory . , , , , , , . , , , ( ), .

Factory , .. . , "Builder" "Prototype", , . , , ...

  • Factory
  • factory
  • Singleton
  • Builder

, factory , . , factory , . , , , . .

. factory, , , . . , , " ". , , , , . , .

factory , , :

  • , , , .
  • , , . Singleton factory.

factory:

  • ,

, , . factory ... .

0
source

One of the advantages is that you can give the factory methods a friendly name. This will help you easily understand which function works in your function and easily support your code in the future. Take a look at this example, hope this helps you.

    public class Contact {

    private Contact(String displayName, String phoneNumber, int contactType){
    //do something
    }

    //then we will have few functon static to get constructor private
    public static createContactUnknow(String phoneNumber){
        return new Contact("","00000000",0);
    }

    public static createContactValid(String displayName, String phoneNumber, int contactType){
        return new Contact(displayName, phoneNumber, contactType);
    }
}

    //then
    Contact myGirlFriend = Contact.createContactValid("xxxx","000000",1);
    Contact unknowFriend = Contact.createContactUnknow("45454545");
0
source

Source: https://habr.com/ru/post/1655560/


All Articles