1 package com.bytezreo.singleton; 2 3 /** 4 * 5 * @Description 单例设计模式 例子-----饿汉式 6 * @author Bytezero·zhenglei! Email:420498246@qq.com 7 * @version 8 * @date 上午9:01:05 9 * @ 10 * 11 */ 12 public class SingletonTest 13 { 14 public static void main(String[] args) { 15 16 //Bank bank = new Bank(); 17 18 Bank bank1 = Bank.getInstance(); 19 20 Bank bank2 = Bank.getInstance(); 21 22 System.out.println(bank1 == bank2); //true 23 24 } 25 } 26 27 28 //饿汉式 29 class Bank 30 { 31 32 //1.私有类的构造器 33 private Bank() 34 { 35 36 } 37 38 //2.内部创建类的对象 39 //4.要求此对象也必须声明为静态的 40 private static Bank instance = new Bank(); 41 42 43 44 //3.提供公共静态的方法,返回类的对象 45 public static Bank getInstance() 46 { 47 return instance; 48 } 49 }