单例模式主要用于创建一个全局共享的实力对象。该实例对象在整个应用程序中只有一个,不会出现更多的实例对象。
基本原理:就是将类的构造方法私有化,这样外部就不能访问了,但是本类内部还是创建对象。
例子一:
public class SimpleManage {
private String name;
private String age;
private static SimpleManage instance = new SimpleManage();
public SimpleManage() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public static SimpleManage getInstance() {
return instance;
}
}
public class Simpleforexam {
public static void main(String[] args) {
SimpleManage sma = new SimpleManage();
sma.setName("mixian");
sma.setAge("25");
SimpleManage smb = new SimpleManage();
smb.setAge("20");
smb.setName("longquan");
System.out.println(sma.getName());
SimpleManage smc = SimpleManage.getInstance();
smc.setName("mixian");
smc.setAge("25");
SimpleManage smd = SimpleManage.getInstance();
smd.setAge("20");
smd.setName("longquan");
System.out.println(smc.getName());
}
}
结果为:mixian,longquan
也就是说:在用户有一个静态方法的时候,如果重新创建实例,实例是新创建的是不变的。
如果直接调用类的静态方法,实例是同一个,是在变化的
实例二:
public class SimpleUser {
private String name;
private String age;
private static SimpleUser instance = null;
public static SimpleUser getInstance() {
if(instance ==null){
instance = new SimpleUser();
return instance;
}
return instance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
SimpleUser su1 = SimpleUser.getInstance();
su1.setName("mixian");
su1.setAge("25");
SimpleUser su2 = SimpleUser.getInstance();
su2.setName("longquan");
su2.setAge("22");
System.out.println(su1.getName());
SimpleUser su3 = new SimpleUser();
su3.setName("mixian");
su3.setAge("25");
SimpleUser su4 = new SimpleUser();
su4.setName("longquan");
su4.setAge("22");
System.out.println(su3.getName());
结果为:longquan,mixian
两种方式都可以创建单例模式。