单例模式

设计模式:对问题行之有效的解决方式。其实它是一种思想。
java中23种设计模式:
1.单例设计模式。
解决问题:就是可以保证一个类在内存中的对象唯一性。

class Single
{
    private  Single(){}

    private static Single s = new Single();

    public static  Single getInstance()
    {
        return s;
    }
}

class SingleDemo 
{
    public static void main(String[] args) 
    {
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();

        s1.setNum(23);

        System.out.println(s2.getNum());
//        Single s1 = new Single();
//        Single s2= new Single();
//        s1.setNum(30);
//        System.out.println(s2.getNum());

//        Student s1 = new Student();
//        s1.setAge(30);
//
//        Student s2 = new Student();
//        s2.setAge(12);

        Student s1 = Student.getStudent();
        Student s2 = Student.getStudent();
    }
}

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;
    }
}

 

posted @ 2013-06-10 16:55  为了这有限的生命  阅读(133)  评论(0编辑  收藏  举报