设计模式(二)单例设计模式

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


我的理解:

1、其实单例模式也就是将一个方法设计成操作系统的临界资源。 

2、只能同时被一个进程所使用,用完后,才能被另一个进程使用。


想要保证对象唯一:

1、为了避免其他程序过多建立该类对象。先禁止其他程序建立该类对象
2、为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象。
3、为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式。


代码体现:

1、将构造函数私有化。
2、在类中创建一个本类对象。
3、提供一个方法可以获取到该对象。

 

简洁的例子:

(饿汉式)

class Student

{

    private int age;

    private static Student s = new Student();

    private Student(){}

    public static Student getStudent()

    {

        return s;

    }

    public void setAge(int age)

    {

        this.age = age;

    }

    public int getAge()

    {

        return age;

    }

}

 

class SingleDemo 

{

    public static void main(String[] args) 

    {

        Student s1 = Student.getStudent();

        Student s2 = Student.getStudent();

        s1.setAge(12);

        System.out.println(s2.getAge);

    }

}

 

 

单例设计模式模型:

 

饿汉式:

1、先初始化对象。

2、大多数程序员最爱用,也是最安全的单例用法。

 

class Single

{

    private static Single s = new Single();

    private Single(){}

    public static Single getInstance()

    {

        return s;

    }

}

 

 

懒汉式:

1、对象是方法被调用时,才初始化,也叫做对象的延时加载。

2、Single类进内存,对象还没有存在,只有调用了getInstance方法时,才建立对象。

 

class Single

{

    privatestatic Single s =null;

    private Single(){}

    public static Single getInstance()

    {

        if(s==null)

        {

            synchronized(Single.class)

            {               

                if(s==null)

                    s = new Single();

            }

        }

        return s;

    }

}

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/firstrate/p/3533561.html