public class SingleModel {
private int a,b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
private SingleModel() {
}
public static SingleModel getInstance() {
return SingleInstance.INSTANCE.getIns();
}
private enum SingleInstance {
INSTANCE;
private SingleModel singleModel;
SingleInstance() {
singleModel = new SingleModel();
}
private SingleModel getIns() {
return singleModel;
}
}
}
public class Main {
public static void main(String[] args) {
/**
* 单例模式
* */
SingleModel instance = SingleModel.getInstance();
instance.setA(10);
instance.setB(20);
System.out.println("instance.getA() = " + instance.getA());
System.out.println("instance.getB() = " + instance.getB());
SingleModel instance1 = SingleModel.getInstance();
System.out.println("instance1.getA() = " + instance1.getA());
System.out.println("instance1.getB() = " + instance1.getB());
if (instance == instance1) {
System.out.println("equal");
} else System.out.println("error");
if (instance.equals(instance1)){
System.out.println("equal");
}else System.out.println("error");
}
}
运行结果如下
G:\jdk\bin\java.exe -javaagent:G:\IDEA\lib\idea_rt.jar=65096:G:\IDEA\bin -Dfile.encoding=UTF-8 -classpath G:\GITHUB\DesignPattern\target\classes Main
instance.getA() = 10
instance.getB() = 20
instance1.getA() = 10
instance1.getB() = 20
equal
equal
Process finished with exit code 0
“==”比较的地址和“equal”比较的内容全都相等,可以看到instance和instance1是相同的两个对象,可以证明单例模式建设成功。