zoukankan      html  css  js  c++  java
  • 单例模式创建

    饿汉式

    public class Singleton{
        public final static INSTANCE = new Singleton();
        private Singleton(){
            
        }
    }
    
    /*枚举类型限制对象个数,当我们只写一个就变成了单例模式
    */
    public enum Singleton(){
        INSTANCE
    }
    
    public class Singleton{
        public static final INSTANCE;
        String info;
        static{
            //适合创建对象是否需要一些文件的初始化之类的工作
            Propereties pro = new Propereties();
            pro.load(Singleton.class.getClassLoader().getResourcesAsStream(类路径下的文件));
            INSTANCE = new Singleton(pro.property("info"));
        }
        privat Singleton(String info){
            this.info = info;
        }
    }
    

    懒汉式

    //线程不安全
    public class Singleton{
        private static final INSTANCE;
        private Singleton(){
            
        }
        public Singleton getInstance(){
            if(INSTANCE == null){
    	      INSTANCE = new Singleton();
            }
            return INSTANCE;
        }
    }
    
    //线程安全
    public class Singleton{
        private static final INSTANCE;
        private Singleton(){
            
        }
        public Singleton getInstance(){
     		synchronized(Singleton.class){//加锁
            if(INSTANCE == null){
    		INSTANCE = new Singleton();
            }
            return INSTANCE;
            }
        }
    }
    
    //线程安全:静态内部类
    public class Singleton{
        
        public static class Inner{
            private static final INSTANCE = new Singleton();
        }
           public Singleton getInstance(){
    
            return Inner.INSTANCE;
        }
        
    }
    
  • 相关阅读:
    android 加入关屏
    网址导航收集
    OpenStack 中文社区
    Truncate 删除数据
    c# 实体类生成工具
    .net 关系
    html中,播放 flash
    Axis2.0+WebService的使用
    xfire java web服务器引擎
    修复 google paly
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13410728.html
Copyright © 2011-2022 走看看