您的位置:首页 > 编程语言 > Java开发

单例模式

2016-07-26 20:32 363 查看
饿汉式单例
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}


懒汉式单例

    public class Singleton {

        private static Singleton singleton;

        private Singleton(){}

        public static synchronized Singleton getInstance(){

            if(singleton==null){

                singleton = new Singleton();

            }

            return singleton;

        }

    }


Java code?
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49
package
 
com;


 

/**


 
* <p>


 
* Title:


 
* </p>


 
*


 
* <p>


 
* Description:


 
* </p>


 
*


 
* <p>


 
* Copyright: 转载请注明出处http://blog.csdn.net/sunyujia/


 
* </p>


 
*


 
* @author 孙钰佳


 
* @main sunyujia@yahoo.cn


 
* @date Oct 5, 2008 6:07:40 PM


 
*/


public
 
class
 
Test {


    
static
 
{


        
System.out.println(
"我是用来做测试的,传统的单例模式会在这个时机被实例化"
);


    
}


 

    
public
 
static
 
Test getInstance() {


        
return
 
TestInstance.getInstance();


    
}


 

    
private
 
Test() {


        
System.out.println(
"oh! test"
);


    
}


 

    
private
 
static
 
class
 
TestInstance {


        
private
 
static
 
Test instance = 
new
 
Test();


 

        
private
 
TestInstance() {


        
}


 

        
private
 
static
 
Test getInstance() {


            
return
 
instance;


        
}


    
};


 

    
public
 
static
 
void
 
main(String[] args) {


        
System.out.println(Test.
class
);


        
System.out.println(
"========================"
);


        
System.out.println(Test.getInstance());


    
}


}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 单例模式