Advertisement

高德面试社招

阅读量:

单例模式

什么是单例模式?它是指在整个程序运行期间,在内存中只会创建且仅创建一次的对象的设计模式。

饿汉模式:

饿汉模式是在类加载过程中,将对象实例创建出来,等待程序使用

复制代码
 public class Singletion{

    
     
    
  
    
     private static Singletion instance = new Singletion();
    
     private Singletion(){};
    
     public static Singletion getSingletion(){
    
     return instance;
    
  
    
     }
    
  
    
 }
    
    
    
    
    AI写代码

懒汉模式:

真正需要使用 对象时才去创建该单例类对象

多线程安全问题、性能问题,调用对象前先判断

复制代码
 public class Singlation{

    
     private static  Singlation singlation = null;
    
     private Singlation(){};
    
     public static synchronized Singlation getSinglation(){
    
     if(Singlation == null){
    
         sychornized(Singlation.class){
    
             if(singlaiton == null){
    
                 singlation = new Singlation();
    
             }
    
         }
    
     } return singlation;
    
     }
    
 }
    
    
    
    
    AI写代码

枚举生成单例模式

复制代码
 public enum Singlation{

    
  
    
     INSTANCE;
    
     public void doSomething(){
    
     System.out.print("hello world");
    
     }
    
  
    
  
    
 }
    
    
    
    
    AI写代码

设计一个多线程实例:

复制代码
 public class Test{

    
     public static void main(String[]args){
    
  
    
     Runnable r = new Runnable(){
    
         @override
    
         public void run(){
    
             System.out.println("A")
    
         }
    
     };
    
     Thread a = new Thread(r);
    
     t.start();
    
     }
    
  
    
  
    
 }
    
    
    
    
    AI写代码

全部评论 (0)

还没有任何评论哟~