当前位置: 代码迷 >> 综合 >> Java | 单例设计模式
  详细解决方案

Java | 单例设计模式

热度:21   发布时间:2024-02-20 02:01:06.0
  1. 面向对象------单例设计模式

设计模式:

 * 对问题行之有效的解决方式,其实是一种思想。有24种,什么语言都适用

  1.单例设计模式

 * 解决的问题:就是可以保证一个类在内存中的对象唯一性

Part 1

package exercise1;

class Single{

//1.私有化该类构造函数

private Single() {}

//2.通过new 在本类中创建一个本类对象

static Single s = new Single();

//3.定义一个共有的方法,将创建的对象返回。

public static Single getInstance() {     

//single 是因为要返回本类对象,返回值就是本类

return s;  //返回创建的对象

}

}

 

 

public class Day13_SingleDemo {

public static void main(String[] args) {

Single ss = Single.getInstance();  //通过类名调用  ,public  Single getInstance()以及 Single s = new Single();须是静态,加static

System.out.println();

}

}

 

Part 2

class Single{

//1.私有化该类构造函数

private Single() {}

//2.通过new 在本类中创建一个本类对象

private static Single s = new Single();//为了可控 把成员变量私有化

//3.定义一个共有的方法,将创建的对象返回。

public static Single getInstance() {     //single 是因为要返回本类对象,返回值就是本类

return s;  //返回创建的对象

}

}

public class Day13_SingleDemo {

public static void main(String[] args) {

Single s1 = Single.getInstance();  

Single s2 = Single.getInstance();

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

}

}

 

Part 3  单例设计模式 应用

(1)内存中有两个对象

  class Test{

private int num;

public void setNum(int num) {

this.num = num;

}

public int getNum() {

return num;

}

}

 

 

 

public class Day13_SingleDemo {

public static void main(String[] args) {

Test t1 = new Test();

Test t2 = new Test();

t1.setNum(14);

t2.setNum(24);

System.out.println(t1.getNum());

System.out.println(t2.getNum());

}//输出 14 24

}

 

(2)保证Test类在内存中的对象唯一性  加入三步动作

class Test{

private int num;

//1.将构造函数私有化

private Test(){};

//2.通过new在本类中创建一个本类对象

 private  static Test test = new Test();

//3.定义一个共有的方法,将创建的对象返回

 public static  Test getInstance(){

return test;

}

public void setNum(int num) {

this.num = num;

}

 

public int getNum() {

return num;

}

}

 

public class Day13_SingleDemo {

public static void main(String[] args) {

       Test t1 = Test.getInstance();

       t1.setNum(14);

       Test t2 = Test.getInstance();

       t2.setNum(20);

System.out.println(t1.getNum());

System.out.println(t2.getNum());

}//结果都是 20 20 保证了唯一性

}

 

 

 

饿汉式、懒汉式 单例设计模式

开发用饿汉式多。面试用懒汉式多。

package exercise1;

//  类一加载对象就已经存在

//饿汉式(饿的不行,类一加载进行,马上开始创建)

class Single1{

private static Single1 s = new Single1();

private Single1() {}

public static Single1 getInstance() {

return s;

}

}

 

 

//类加载进来,没有对象。

//只有在调用getIntance方法时,对象才在堆内存中生成(创建对象)

//也叫延迟加载形式 ,称为懒汉式(一开始不做,等到真正用到时才做)

class SingleLanhan{

private SingleLanhan() {}

 private static SingleLanhan sl =null;

 public static SingleLanhan getInstance() {

 if(sl==null)

 sl = new SingleLanhan();

 return sl;

 }

}