单例模式



package
adanlimoshi.test001; /*
* 单例模式:创建的对象的地址都指向同一个
* 步骤:构造方法私有化 - 对外提供一个 公开的 静态的 获取当前类型对象的方法 - 提供一个当前类型的静态方法
* | | |
* private Singleton(){} public static Singleton getInstance(){} private static Singleton s;
*
* * 设计模式:可以重复利用的解决方案 * * 单例模式是23种设计模式中最简单的一种设计模式 * * 为了解决什么问题? * 为了保证JVM中某一个类型的java对象永远只有一个 * * 为了节省内存的开销
*/ public class UserTest { public static void main(String args[]){ UserTest u1 = new UserTest(); UserTest u2 = new UserTest(); //==两边如果是基本数据类型,可以比较这两个基本数据类型是否相等 //==两边如果是引用数据类型,则比较的是内存地址 System.out.println(u1==u2); //false } }
package adanlimoshi.test001;

/*
 * 实现单例模式
 *         1、构造方法私有化
 *         2、对外提供一个公开的静态的获取当前类型对象的方法
 *         3、提供一个当前类型的静态方法
 * 
 * 单例模式分为两种:
 *         饿汉式单例:在类加载阶段就创建了对象
 *         懒汉式单例:用到对象的时候才会创建对象(比较好)
 */
public class Singleton { //懒汉式单例

    //静态变量
    private static Singleton s;
//不用写成Singleton s = null //因为在静态方法运行,所以要定义为静态变量。静态变量会默认赋空值,而且只赋值一次 //将构造方法私有化 private Singleton(){} //对外提供一个公开获取Singleton对象的方法 public static Singleton getInstance(){ //Singleton类型的getInstance的方法(相当于int i) if(s == null){ s = new Singleton(); } return s; } }

package adanlimoshi.test001;

public class Test01 {

    public static void main(String[] args) {

        /*
        Singleton s1 = new Singleton();
        Singleton s2 = new Singleton();
        
        System.out.println(s1 == s2);
        */
        //非单例
        
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        
        System.out.println(s1 == s2); //true
    }

}
package adanlimoshi.test001;

//饿汉式
public class Customer {

    //类加载时只执行一次
    private static Customer c = new Customer();
    
    //构造方法私有化
    private Customer(){}
    
    //提供公开的方法
    public static Customer getInstance(){
        return c;
    }
}
package adanlimoshi.test001;

public class Test02 {

    public static void main(String[] args) {

        Customer c1 = Customer.getInstance();
        Customer c2 = Customer.getInstance();
        
        System.out.println(c1 == c2); //true
    }

}

 

posted @ 2020-08-13 20:06  Lerresino  阅读(157)  评论(0)    收藏  举报