设计模式之单例模式

设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易地被他人理解、保证代码可靠性。毫无疑问,设计模式于己于人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石脉络,如同大厦的结构一样。

单例模式是23种设计模式的一种。单例模式顾名思义,对于一个类只能创建一个实例对象。

单例模式的要点是:

1.构造器私有化

2.创建一个私有的静态实例化对象

3.创建一个公开的获得对象的方法

eg:

1.饿汉模式

 class Student{

//私有化构造器

pivate Student(){

}

//创建一个私有的静态的实例化对象

private static Student stu=new Student();

//.创建一个公开的获得对象的方法

public static Student getStudent(){

return stu;

}

public class TestStudent{

public static void main(String[] args){

//main方法通过类方法获得单例并应用给st变量

Student st=Student.getStudent();

}

}

2.懒汉模式

 class Student{

//私有化构造器

pivate Student(){

}

//命名一个私有的静态的类变量引用

private static Student st;

//.创建一个公开的获得对象的方法,并创建对象

public static Student getStudent(){

if(st==null){

st=new Student();

}

return stu;

}

public class TestStudent{

public static void main(String[] args){

//main方法通过类方法获得单例并应用给st变量

Student st=Student.getStudent();

}

}

原文地址:https://www.cnblogs.com/hitnmg/p/9252842.html