单例设计模式

2020-12-07  本文已影响0人  冯宏志
package com.atguigu.java;

public class Test {                //饿汉式
    public static void main(String[] args) {
        Bank bank1 = Bank.getInstance();
        System.out.println(bank1);
    }
}

class Bank {
    private Bank() {
        
    }
    
    private static Bank instance = new Bank();
    
    public static Bank getInstance() {
        return instance;
    }
}
package com.atguigu.java;

public class Test1 {                        //饱汉式
    public static void main(String[] args) {
        Order order1 = Order.getInstance();
        System.out.println(order1);
    }
}

class Order{
    private Order() {
        
    }
    
    private static Order instance = null;
    
    public static Order getInstance() {
        if(instance == null) {
            instance = new Order();
            return instance;
        }
        return instance;
    }
}

单例模式应用场景

上一篇下一篇

猜你喜欢

热点阅读