Singleton(シングルモード)
4547 ワード
public class Singleton {//
public String name;
private static Singleton instance=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton ts1 = Singleton.getInstance();
ts1.setName("jason");
Singleton ts2 = Singleton.getInstance();
ts2.setName("0539");
ts1.printInfo();
ts2.printInfo();
if(ts1 == ts2){
System.out.println(" ");
}else{
System.out.println(" ");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printInfo() {
System.out.println("the name is " + name);
}
}
/* public class Singleton{
public String name;
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null)
instance=new Singleton();
}
}
return instance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printInfo() {
System.out.println("the name is " + name);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton ts1 = Singleton.getInstance();
ts1.setName("jason");
Singleton ts2 = Singleton.getInstance();
ts2.setName("0539");
ts1.printInfo();
ts2.printInfo();
if(ts1 == ts2){
System.out.println(" ");
}else{
System.out.println(" ");
}
}
}*/