public class Test {
public static void main(String[] args) {
Name name = Name.getNameInstance();
name.setFirstName("J.K");
name.setLastName("Rolling");
Name name2 = Name.getNameInstance();
System.out.println(name);
System.out.println(name2);
System.out.println(name == name2);
System.out.println(name.equals(name2));
}
}
class Name {
private String firstName;
private String lastName;
private Name() {
}
private static Name name = null;
public static Name getNameInstance() {
if (name == null) {
name = new Name();
}
return name;
}
/**
* 单例模式 核心代码--------------------
*
*
*
*/
// private static final Name name = new Name();
//
// public static Name getNameInstance() {
// return name;
// }
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return getFirstName() + " " + getLastName();
}
}