Java | 单例设计模式

  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;

 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值