标签:instance main test pac bsp 必须 class let 单例设计模式
1 package com.yhqtv.test; 2 //饿汉式 3 public class SingletonTest1 { 4 public static void main(String[] args) { 5 Bank bank1 = Bank.getIntstance(); 6 Bank bank2 = Bank.getIntstance(); 7 8 System.out.println(bank1==bank2); 9 } 10 11 } 12 class Bank{ 13 14 //1.私有化的构造器 15 private Bank(){ 16 17 } 18 19 //2、内部创建类的对象 20 //4.要求此对象也必须声明为静态 21 private static Bank intstance=new Bank(); 22 23 //3.提供公共的静态的方法,返回类的对象 24 public static Bank getIntstance(){ 25 return intstance; 26 } 27 28 }
1 package com.yhqtv.test; 2 //懒汉式 3 public class SingletonTest2 { 4 public static void main(String[] args) { 5 Order order1=Order.getInstance(); 6 Order order2=Order.getInstance(); 7 8 System.out.println(order1==order2); 9 10 } 11 12 } 13 class Order{ 14 15 //1.私有化的构造器 16 private Order(){ 17 18 } 19 20 //2、s声明当前类对象,没有初始化 21 //4.此对象也必须声明static 22 private static Order instance=null; 23 24 //3.声明public、static的返回当前类的对象方法 25 public static Order getInstance(){ 26 if(instance==null){ 27 instance=new Order(); 28 29 } 30 return instance; 31 } 32 }
标签:instance main test pac bsp 必须 class let 单例设计模式
原文地址:https://www.cnblogs.com/yhqtv-com/p/12767167.html