当前位置: 移动技术网 > IT编程>开发语言>Java > java设计模式--单例模式

java设计模式--单例模式

2019年07月11日  | 移动技术网IT编程  | 我要评论

单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

当我们需要一个类只有一个实例时,我们就可以使用单例模式,单例模式分为两种,懒汉式单例和饿汉式单例。首先我们看懒汉式单例

public class superme {

    /**
     * volatile 确保superme在线程中同步
     */
    private static volatile superme superme = null;

    /**
     * private避免类在外部被实例化
     */
    private superme(){
        system.out.println("i'm the superme");
    }

    public static synchronized superme getinstance(){
        if(superme == null){
            superme = new superme();
        }else {
            system.out.println("no second allowed");
        }
        return superme;
    }

    public void getname(){
        system.out.println("hitler");
    }
}

测试类

public class lazysingleton {
    public static void main(string[] args) {
        superme superme = superme.getinstance();
        superme.getname();
        superme superme2= superme.getinstance();
        superme2.getname();
        if(superme ==superme2){
            system.out.println("hitler is a dictator");
        }else {
            system.out.println("they are not same");
        }
    }
}

测试结果:

i'm the superme
hitler
no second allowed
hitler
hitler is a dictator

懒汉式单例的特点是类加载时没有生成实例,只有当第一次调用getinstance()方法时才会去创建这个单例。

饿汉式单例的例子如下:

public class hungrysuperme {
    private static hungrysuperme hungrysuperme = new hungrysuperme();

    private hungrysuperme() {
        system.out.println("i'm the hungrysuperme");
    }

    public static hungrysuperme gethungrysuperme() {
        return hungrysuperme;
    }
}

测试类

public class hungrysingleton {

    public static void main(string[] args) {
        hungrysuperme hungrysuperme = hungrysuperme.gethungrysuperme();
        hungrysuperme hungrysuperme2 = hungrysuperme.gethungrysuperme();
        if(hungrysuperme == hungrysuperme2){
            system.out.println("i'm the only one");
        }else {
            system.out.println("i'm not at the top");
        }
    }
}

测试结果:

i'm the hungrysuperme
i'm the only one

 饿汉式单例在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以是线程安全的,可以直接用于多线程而不会出现问题。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网