singleton单例模式

单例设计模式

单例设计模式概述
    单例模式就是要确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供
    
优点:
    在系统内存中只存在一个对象,因此可以解决系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能
    
缺点:
    没有抽象层,因此扩展很难
    职责过重,在一定程度上违背了单一职责

package com.singleton;
/*
 * 单例模式的思想:
 *     内存中只能有一个该对象
 *         分析:
 *             只能有一个对象,说明不能对外提供构造
 *             对象只能由自己提供
 *             外界怎么访问到你的方法呢?不能实例化你对象。所以获得方法是静态
 *             方法静态所以属性也必须静态,但是属性不能直接被外界拿到啊。所以属性加私有
 * 
 * 现在这种单例模式称为饿汗式
 *         表现在:这个类还没使用就创建了一个需要的而对象。
 */
public class Student {
    private Student(){
        
    }
    private static Student s=new Student();
    public static Student createInstance(){
        return s;
    }
}
package com.singleton;

public class StudentDemo {
    public static void main(String[] args) {
        Student s=Student.createInstance();
        Student s1=Student.createInstance();
        System.out.println(s1==s);
        System.out.println(s1);
        System.out.println(s);
    }
}
package com.singleton;
/*
 * 懒汉式
 *         表现在:
 *             1、延迟加载(需要的时候才创建对象)
 *             2、线程不安全,通常需要加上一下同步锁
 */
public class Teacher {
    private Teacher(){
        
    }
    private static Teacher t=null;
    public static synchronized Teacher createInstance(){
        if(t==null){
            t=new Teacher();
        }
        return t;
    }
}
package com.singleton;

public class TeacherDemo {
    public static void main(String[] args) {
        Teacher t=Teacher.createInstance();
        Teacher t1=Teacher.createInstance();
        System.out.println(t==t1);
        System.out.println(t1);
        System.out.println(t);
        
    }
}
单例模式例子:
package com.singleton;

import java.io.IOException;

/*
 * Runtime
 * 这个类是单例模式
 * 一个exec(String command)可以执行dos命令
 * 
 */
public class RuntimeDemo {
    public static void main(String[] args) throws IOException {
        Runtime r=Runtime.getRuntime();
        // 打开计算器 r.exec("calc");
        //打开记事本 r.exec("notepad");
//        r.exec("shutdown -s -t 10000");
        r.exec("shutdown -a");
    }
}
原文地址:https://www.cnblogs.com/aigeileshei/p/5609216.html