java基础之对象创建
java是一门面向对象的语言。使用java最基本的操作就是创建对象 new Object();。但你千万别小看了这个new。以不同方法来new一个对象可能导致你系统性能好几倍的差距。下面就来八一八各种创建方式的优缺点。
1. new 方式。这种方式有优点是使用简单。如果类构造方法不需要参数,则连构造方法都可以省略。而new 的每个实例都相对独立。除静态方法或属性,不会相互影响。缺点就是太占内存,另外如果有多个参数。需编写多个构造方法,使用复杂。
2. 静态工厂方法。如Boolean 中的valueOf 方法:
public static Boolean valueOf(boolean b){ return b ? Boolean.TRUE : Boolean.FALSE; }这种方式优点有: 创建方法有名称、不必每次调用都新建对象、可以返回原型的子类型、使用泛型参数时可以更简洁。
public static <K,V> HashMap(K,V) newInstance(){ return new HashMap<K,V>(); } //调用 Map<Sting,List<String>> map = HashMap.newInstance();缺点是如果没有公有或protected构造方法不能被子类化、静态工厂方法与其他静态方法没有任何区别
3.利用建造器模式。优点 :解决多可选参数构造器参数传递与检测问题。
public class Test { private String name; private String no; private int age; private float height; private Test(Builder b){ this.name = b.name; this.age = b.age; this.no = b.no; this.height = b.height; } public static class Builder{ private String name; private String no; private int age; private float height; public Builder(String name) { this.name = name; } public Builder no(String no){ this.no = no ; return this; } public Builder age(int age){ this.age = age ; return this; } public Builder height(float height){ this.height = height ; return this; } public Test build(){ return new Test(this); } } }