enum(枚举)实现单例模式

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是相同的两个对象,可以证明单例模式建设成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值