Effective Java 第一条:考虑用静态工厂方法代替构造器


平时大家常用的String类源码就是典型的静态工厂方法:

/**
 * Returns the string representation of the given double.
 */
public static String valueOf(double value) {
    return Double.toString(value);
}

/**
 * Returns the string representation of the given float.
 */
public static String valueOf(float value) {
    return Float.toString(value);
}

/**
 * Returns the string representation of the given int.
 */
public static String valueOf(int value) {
    return Integer.toString(value);
}

/**
 * Returns the string representation of the given long.
 */
public static String valueOf(long value) {
    return Long.toString(value);
}
 
  
再如单例中的getInstance()方法。
 
  

静态工厂方法最大的优点是不用实例化类。

我们平时写类一般是这样写的:

定义一个人类,获取姓名年龄。

Man man = new Man(18,"小明");

man.getName();

man.getAge();

public class Man {
    private String name;
    private int age;

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

用静态工厂方法写:

public class Man {
    private String name;
    private int age;

    private final static Man man = new Man("小明",18);
    private final static Man woman = new Man("小红",19);

    private Man(String name, int age){
        this.name = name;
        this.age = age;
    }

    public static Man getMan(){
        return man;
    }

    public static Man getWoman(){
        return woman;
    }

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }

}

获取姓名和年龄就可以这样啦:
Man.getMan().getName()
Man.getWoman().getAge()
 
  
 
  

你可能感兴趣的:(Java,Effective,Java)