Java单利模式
2017-02-13 本文已影响20人
写一本2000000的书
/**
* 解决内存中只有一个内存空间的对象
* 对象唯一
* 为了避免其他程序过多的建立该类的对象,先禁止其他程序建立对象,
* 还为了让其他程序 能访问该对象,在本类中自定义一个对象
* 对外提供访问方式
*
*
* */
class Single{
private int num;
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s==null)
s = new Single();
return s;
}
}
/*
class Single{
private Single(){
}
private int num;
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static Single s = new Single();
public static Single getInstance(){
return s;
}
}
*/
public class singleDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Single ss = Single.getInstance();
Single sss = Single.getInstance();
ss.setNum(40);
System.out.println(sss.getNum());
sss.setName("zhang");
System.out.println(ss.getName());
}
}