码迷,mamicode.com
首页 > 其他好文 > 详细

单态设计模式(Singleton pattern)

时间:2015-08-17 13:43:05      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:

单态(单例)设计模式

  单态设计模式(Singleton pattern)就是要保证在整个程序中某个类只能存在一个对象,这个类不能再创建第二个对象。

单态设计模式的写法

  私有化构造函数,阻止创建新对象。

单例设计模式:
在内存中对象只有一个存在。
*/
//饿汉式
class Student
{
    private Student(){}

    private static Student s = new Student();

    public static Student getInstance()
    {
        return s;
    }
}
//懒汉式
class Teacher
{
    private Teacher(){}

    private static Teacher t;

    public static Teacher getInstance()
    {
        if(t==null)
        {
            t = new Teacher();
        }
        return t;
    }
}

class SingletonDemo 
{
    public static void main(String[] args) 
    {
        /*
        Student s1 = new Student();
        Student s2 = new Student();
        System.out.println(s1==s2);
        */

        Student s1 = Student.getInstance();
        Student s2 = Student.getInstance();
        System.out.println(s1==s2);

        Teacher t1 = Teacher.getInstance();
        Teacher t2 = Teacher.getInstance();
        System.out.println(t1==t2);
    }
}

 

单态设计模式(Singleton pattern)

标签:

原文地址:http://www.cnblogs.com/cjcblogs/p/4736314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!