设计模式(单例模式)
单例模式:保证类在内存中只有一个对象。
如何保证类在内存中只有一个对象呢?
* A:把构造方法私有
* B:在成员位置自己创建一个对象----私有化并静态化
* C:通过一个公共的方法提供访问
*/
单例模式(饿汉式)
package cn.itcast_03; public class Student { // 构造私有 private Student() { } // 自己造一个 // 静态方法只能访问静态成员变量,加静态 // 为了不让外界直接访问修改这个值,加private private static Student s = new Student(); // 提供公共的访问方式 // 为了保证外界能够直接使用该方法,加静态 public static Student getStudent() { return s; } }
package cn.itcast_03; /* * 单例模式:保证类在内存中只有一个对象。 * * 如何保证类在内存中只有一个对象呢? * A:把构造方法私有 * B:在成员位置自己创建一个对象 * C:通过一个公共的方法提供访问 */ public class StudentDemo { public static void main(String[] args) { // Student s1 = new Student(); // Student s2 = new Student(); // System.out.println(s1 == s2); // false // 通过单例如何得到对象呢? // Student.s = null; Student s1 = Student.getStudent(); Student s2 = Student.getStudent(); System.out.println(s1 == s2); System.out.println(s1); // null,cn.itcast_03.Student@175078b System.out.println(s2);// null,cn.itcast_03.Student@175078b } }
单例模式(懒汉式)
/*
* 单例模式:
* 饿汉式:类一加载就创建对象
* 懒汉式:用的时候,才去创建对象
*
* 面试题:单例模式的思想是什么?请写一个代码体现。
*
* 开发:饿汉式(是不会出问题的单例模式)
* 面试:懒汉式(可能会出问题的单例模式)
* A:懒加载(延迟加载)
* B:线程安全问题
* a:是否多线程环境 是
* b:是否有共享数据 是
* c:是否有多条语句操作共享数据 是
*/
package cn.itcast_03; /* * 单例模式: * 饿汉式:类一加载就创建对象 * 懒汉式:用的时候,才去创建对象 * * 面试题:单例模式的思想是什么?请写一个代码体现。 * * 开发:饿汉式(是不会出问题的单例模式) * 面试:懒汉式(可能会出问题的单例模式) * A:懒加载(延迟加载) * B:线程安全问题 * a:是否多线程环境 是 * b:是否有共享数据 是 * c:是否有多条语句操作共享数据 是 */ public class Teacher { private Teacher() { } private static Teacher t = null; public synchronized static Teacher getTeacher() { // t1,t2,t3 if (t == null) { //t1,t2,t3 t = new Teacher(); } return t; } }
package cn.itcast_03; public class TeacherDemo { public static void main(String[] args) { Teacher t1 = Teacher.getTeacher(); Teacher t2 = Teacher.getTeacher(); System.out.println(t1 == t2); System.out.println(t1); // cn.itcast_03.Teacher@175078b System.out.println(t2);// cn.itcast_03.Teacher@175078b } }
单例模式的Java代码体现Runtime类
package cn.itcast_03; import java.io.IOException; /* * Runtime:每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。 * exec(String command) */ public class RuntimeDemo { public static void main(String[] args) throws IOException { Runtime r = Runtime.getRuntime(); // r.exec("winmine"); // r.exec("notepad");-----打开记事本软件 // r.exec("calc");---打开计算器软件 // r.exec("shutdown -s -t 10000");----规定指定的时间关机 r.exec("shutdown -a");//----取消规定的关机时间 } } /* * class Runtime { * private Runtime() {} * private static Runtime currentRuntime = new Runtime(); * public static Runtime getRuntime() { * return currentRuntime; * } * } */

浙公网安备 33010602011771号