单态(单例)设计模式
单态设计模式(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); } }
时间: 2024-10-13 00:07:50