码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-12-30 18:35:25      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:ima   声明   start   访问   技术   query   pen   lan   tor   

步骤

1.属性私有,静态,为了让静态方法调用

2.构造器私有,饿汉在构造器里就常见对象

3.提供静态的访问方法

技术分享
 1 package jquery;
 2 
 3 
 4 public class Singleton {
 5 
 6     //属性私有,因为提供获取对象的方法所以static声明
 7     private static Singleton singleton;
 8     
 9     //构造器私有,别人没法new对象
10     private Singleton(){
11         //在构造器就吃,属于饿汉模式
12         singleton=new Singleton();
13     }
14     
15     public static Singleton getSingleton(){
16         return singleton;
17     }
18 }
View Code

懒汉模式

技术分享
 1 package jquery;
 2 
 3 public class Singletonlan {
 4 
 5     private static Singletonlan singletonlan;
 6     
 7     private Singletonlan(){
 8         
 9     }
10     
11     public static Singletonlan getSingletonlan(){
12         if(singletonlan==null){
13             return new Singletonlan();
14         }
15         return null;
16     }
17 }
View Code

 

单例模式

标签:ima   声明   start   访问   技术   query   pen   lan   tor   

原文地址:http://www.cnblogs.com/javaweb2/p/6237725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!