java 单例模式

来源:互联网 发布:淘宝是日本的 编辑:程序博客网 时间:2024/06/14 10:27

一般有两种

直接加载与延迟加载(多线程时会出现重复加载)

另外effiect java 里面提供了一种单例方法,枚举

package com.huawei.sington;/** * 单例模式 * @author Administrator * */public class singtonTest {//直接加载,线程安全private static singtonTest  st= new singtonTest();private singtonTest(){}public static singtonTest getInstance(){return st;}public static void main(String[] args) {weeked.one.getInfo();}}class singtonTest1{//延迟加载private static singtonTest1 st1 = null;private singtonTest1(){}public singtonTest1 getInstance(){//线程非安全synchronized (this) {if(st1==null){st1 = new singtonTest1();return st1;}}return st1;}}enum weeked{one;weeked(){System.out.println("加载一次");}public void getInfo(){System.out.println("--weekde");}}class Test{static class  test1{//绝对的单例模式}}


 
原创粉丝点击