单例设计模式
类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只能提供一个取得其对象实例的方法。
我们首先将类的构造器访问权限设置为private,这样,就不能用new操作符在类的外部产生类的对象了,但在类的内部可以产生该类的对象。在类的外部只能通过调用该类的某个静态方法以返回类内部创建的对象,静态方法只能访问类中的静态成员变量,所以,指向类内部产生的该类对象的变量也必须定义成静态的。
单例的饿汉式实现
1 public class hungry {
2 public static void main(String[] args) {
3 Bank bank1 = Bank.getInstance();
4 Bank bank2 = Bank.getInstance();
5
6 System.out.println(bank1 == bank2); //true
7 }
8 }
9
10 class Bank{
11 //1.私有化类的构造器
12 private Bank(){
13
14 }
15 //2.内部创建类对象
16 //4.要求此对象也必须声明为静态的
17 private static Bank instance = new Bank();
18
19 //3.提供公共的静态方法,返回类的对象
20 public static Bank getInstance(){
21 return instance;
22 }
23 }
单例的懒汉式实现(线程不安全方式)
1 public class lazy {
2 public static void main(String[] args) {
3 Order order1 = Order.getInstance();
4 Order order2 = Order.getInstance();
5
6 System.out.println(order1 == order2); //true
7 }
8 }
9
10 class Order{
11 //1.私有化类的构造器
12 private Order(){
13
14 }
15 //2.内部创建类对象
16 //4.要求此对象也必须声明为静态的
17 private static Order instance ;
18
19 //3.提供公共的静态方法,返回类的对象
20 public static Order getInstance(){
21 if(instance == null) instance = new Order();
22 return instance;
23 }
24 }
线程安全:方式一:同步代码块; 方式二:同步方法
1 public class lazy { 2 public static void main(String[] args) { 3 Order order1 = Order.getInstance(); 4 Order order2 = Order.getInstance(); 5 6 System.out.println(order1 == order2); //true 7 } 8 } 9 10 class Order{ 11 //1.私有化类的构造器 12 private Order(){ 13 14 } 15 //2.内部创建类对象 16 //4.要求此对象也必须声明为静态的 17 private static Order instance ; 18 19 //3.提供公共的静态方法,返回类的对象 20 public static Order getInstance(){ 21 if(instance == null) { 22 synchronized(Order.class){ 23 instance = new Order(); 24 } 25 } 26 27 return instance; 28 } 29 }
1 public class lazy { 2 public static void main(String[] args) { 3 Order order1 = Order.getInstance(); 4 Order order2 = Order.getInstance(); 5 6 System.out.println(order1 == order2); //true 7 } 8 } 9 10 class Order{ 11 //1.私有化类的构造器 12 private Order(){ 13 14 } 15 //2.内部创建类对象 16 //4.要求此对象也必须声明为静态的 17 private static Order instance ; 18 19 //3.提供公共的静态方法,返回类的对象 20 public static synchronized Order getInstance(){ 21 if(instance == null) { 22 instance = new Order(); 23 } 24 25 return instance; 26 } 27 }
优点:减少了系统性能开销。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)