Consider static factory methods instead of Constructors

Source: Internet
Author: User
  • Advantage 1. Name

The static factory method can directly transmit a lot of information through the method name, but unlike the traditional constructor method, the name can only be the same as the class name, you can only determine which method to call by passing parameters and comments. A good example:

There is a randomintgenerator class that generates random Integers of the int type. As follows:

public class RandomIntGenerator {private final int min;private final int max;public int next() {...}}

This generator receives two parameters, maximum and minimum, and generates a random number between them. Note that the two attributes min and Max are modified by final, so they must be initialized. You can initialize them when defining them or through the constructor. The constructor is initially as follows:

public RandomIntGenerator(int min, int max) {    this.min = min;    this.max = max;}

Now, we want to provide this function. The client only sets a minimum value and generates an integer between this value and integer. max_value. So we added the second constructor:

public RandomIntGenerator(int min) {    this.min = min;    this.max = Integer.MAX_VALUE;}

So far, everything is normal. However, we also need to provide a constructor to set a maximum value, and then generate an integer between integer. min_value and the maximum value. The third constructor is added as follows:

public RandomIntGenerator(int max) {    this.min = Integer.MIN_VALUE;    this.max = max;}

If you do this, a compilation error occurs: duplicate method randomintgenerator (INT) in type randomintgenerator. What went wrong there? There is no doubt that the constructor has no name. Therefore, a class has only one constructor with a specific method signature. Similarly, you cannot define two methods with the same method signature (the same return value, name, parameter type, and number. This is why the above compilation error occurs when we try to add the constructor randomintgenerator (INT max), because we already have a constructor randomintgenerator (INT min ).

What should we do in such a situation? Fortunately, there are other ways to use: static factory method, return a class instance by using a simple public static method. You may have used this technology unconsciously. Have you ever written Boolean. valueof ?, As shown below:

public static Boolean valueOf(boolean b) {    return (b ? TRUE : FALSE);}

Apply the static factory to the randomintgenerator class to obtain

 public class RandomIntGenerator {

    private final int min;    private final int max;    private RandomIntGenerator(int min, int max) {        this.min = min;        this.max = max;    }    public static RandomIntGenerator between(int max, int min) {        return new RandomIntGenerator(min, max);    }    public static RandomIntGenerator biggerThan(int min) {        return new RandomIntGenerator(min, Integer.MAX_VALUE);    }    public static RandomIntGenerator smallerThan(int max) {        return new RandomIntGenerator(Integer.MIN_VALUE, max);    }    public int next() {...}}

Note that the constructor is private to ensure that the class can only be initialized using the static factory method. And when you use randomintgenerator. Between (10, 20) instead of new randomintgenerator (10, 20) to generate integers, your intention is clearly expressed. It is worth noting that this technology is different from the Gang of Four factory design model. In addition, any class can provide a static factory method to replace the constructor. So what are the advantages and disadvantages of this technology? We have already mentioned the First Advantage of the static factory method: the static factory method has a name. There are two direct advantages:
1. We can provide a meaningful name for the static method.
2. We can provide several constructors with the same parameter types and number of parameters for static methods. This cannot be done in traditional constructors.

 

  • Advantage 2.new object

The static factory method does not need to create a new object every time it is called. A good example is the valueof method in Java. Lang. boolean.

Public static Boolean valueof (Boolean B ){
Return (B? True: false );
}
Objects are not created after multiple calls.
  • Advantage 3. return any subtype of their return type (fan type)

When we not only need to return random int values, we canRandomGeneratorsAdd static factory Method

Public final class randomgenerators {// suppresses default constructor, ensuring non-instantiability. private randomgenerators () {} public static final randomgenerator <integer> getintgenerator () {return New randomintgenerator (integer. min_value, integer. max_value);} public static final randomgenerator <string> getstringgenerator () {return New randomstringgenerator ('');}}
To return a random string, directly call
RandomGenerator.Getstringgenerator (). Get ....
Another example is frequently used.
Maps. newhaskmap () and so on in COM. Google. Common. Collect. (guava)
  • Advantage 4. Can the type of returned object be changed based on input parameters?

Also collect a new hashmap. Traditional Method

Map <string, integer> map = new hashmap <string, integer> ();
The static factory method is used.
Public static <K, V> hashmap <K, V> newhashmap (){
Return new hashmap <K, V> ();
}
You can directly
Map<String, Integer> map =Maps.newHaskMap()
  • Advantage 5. Delayed loading?

For example, in JDBC

Drivermanager. getconnection ()
The connection does not need to be established during the call.

 

Disadvantage

  • 1. if we set the constructor to private in the class and only provide the static factory method to build the object, we will not be able to extend the class through inheritance.
    But this will also encourage usUse combination instead of inheritance to extend the class.
  • 2. The static factory method for building objects is not clearly identified as the constructor, and cannot be separated from other static methods easily.

    If the class only provides static factory methods rather than constructors, it will become difficult to find out how to instantiate a class.
    We can compensate for this disadvantage by following the naming rules of static factory methods:

      • Valueof-the returned instance has the same value as its parameter, which is generally used for type conversion. For exampleBoolean.valueOf(boolean)
      • Of-valueof is a more concise alternative.
      • Getinstance-the returned instance is described using method parameters, but it cannot be said that it has the same value as the parameter. For Singleton, The getinstance parameter is used to return a unique instance.
      • Newinstance-like getinstance, but it can ensure that a new object is returned each time.
      • GetType-the same as getinstance, but the object returned by this method is another different class.
      • Newtype-like GetType, a new object is returned each time.

Reference link: http://honoka.cnblogs.com. Https://yq.aliyun.com/articles/17013.

Consider static factory methods instead of Constructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.