一:通过静态私有成员实现单例模式
(1):私有化构造函数
(2):new静态实例属性对象,加锁。
单例类:
package SinglePag; /* * 构造函数私有化,结合锁+静态的概念 实现单例模式 */ public class SingleDemo { //防止类的实例化 private SingleDemo(){ } //静态 实例 属性 private static SingleDemo singleD; //获取对象实例 (单例的方式 ),锁住当前类(加锁) public synchronized static SingleDemo getInstance(){ if(singleD == null){ singleD = new SingleDemo(); } return singleD; } }
实现:
package SinglePag; public class SingleWinform { public static void main(String[] args) { SingleDemo singleDemo = SingleDemo.getInstance(); System.out.println(singleDemo.hashCode()); SingleDemo singleDemo2 = SingleDemo.getInstance(); System.out.println(singleDemo2.hashCode()); } }
二:静态内部类实现单例模式
(1):私有化构造函数
(2):私有静态内部类,创建静态实例成员对象
(3):静态实例获取方法
单例类:
package SinglePag; public class SingleInnerStatic { //静态内置类 private static class InnerStatic{ //静态私有 实例属性 private static SingleInnerStatic singleInstance; static{ singleInstance = new SingleInnerStatic(); } } //私有化构造函数,防止实例化 private SingleInnerStatic(){ } public static SingleInnerStatic getInstance(){ return InnerStatic.singleInstance; } }
实现:
package SinglePag; public class SingleStaticWinform { public static void main(String[] args) { SingleInnerStatic singleInnerStatic =SingleInnerStatic.getInstance(); System.out.println(singleInnerStatic.hashCode()); SingleInnerStatic singleInnerStatic2 = SingleInnerStatic.getInstance(); System.out.println(singleInnerStatic2.hashCode()); } }
时间: 2024-10-06 20:10:11