Java's static factory method

Many are mentioned in the book to create objects try not to go directly to the constructor new, instead of using static factory methods to replace the constructor

I still do not quite understand at first, then after reading several excellent article, suddenly, write it down for later.

Consider a class:

package com.example.demo;

public class Dog {
    private String name;

    private String color;

    private int age;

    public Dog() {
    }

    public Dog(String name) {
        this.name = name;
    }

    public Dog(String name, String color, int age) {
        this.name = name;
        this.color = color;
        this.age = age;
    }
}

After the problem is that I only want to add a parameter only dog color constructor, but has no way to add, because the argument is the constructor and name of the conflict.

But if I use a static factory method to write, this problem is solved:

package com.example.demo;

public class Dog {
    private String name;

    private String color;

    private int age;

    private Dog() {
    }

    public static Dog newDogWithAllParam(String name, String color, int age) {
        Dog dog = new Dog();
        dog.name = name;
        dog.age = age;
        dog.color = color;
        return dog;
    }

    public static Dog newDogWithName(String name) {
        Dog dog = new Dog();
        dog.name = name;
        return dog;
    }

    public static Dog newDogWithColor(String color) {
        Dog dog = new Dog();
        dog.color = color;
        return dog;
    }
// Getters & Setters
}

The advantage of using a static factory method there are many, such as the following two points:

1. Every time a new object, you can just scheduling method requires it, and each method has different "names", by name I can know is what I attribute to create an object

2. Use static factory methods do not always create a new object because static belong to the class, how many objects so no matter created a class is always only one static objects, so that when you have to create a lot of time to prevent memory objects consume

Guess you like

Origin www.cnblogs.com/caotao0918/p/12072286.html