单例设计模式及其举例

 单例设计模式:一个类只允许有一个对象,将这个对象作为一个全局的访问点,提供出去供大家使用
 

分析:
 * 1.用户只能一个对象
 * 2.全局的访问点:得到的对象就是全局的访问点,如何做到全局?让static去修饰
 * 3.如何提供出去?
 * 4.供大家使用?---单例的功能

 
 * 单例类的作用:1.可以实现两个对象之间的传递
 * 好处:可以让两个对象在完全没有关系的前提下,实现值的传递,降低了耦合性,提高了内聚性
 

//饿汉式--在定义变量的同时完成初始化
class SingleInstance{
    //2.在类的内部创建一个当前类型的属性并赋值---在类的内部得到了当前类的一个对象
    //将变量私有化,让外界无法访问,给变量用static修饰让它成为全局的访问点
     private static SingleInstance singleInstance = new SingleInstance();
    
    //1.将构造方法私有化
    private  SingleInstance() {}    
    //3.使用公共的方法将变量提出去,并将方法设置成静态的
    public static SingleInstance getInstance() {
        return singleInstance;
    }    
}

//懒汉式--开始只是定义变量,什么时候使用什么时候赋值
class SingleInstance1{
    //2.在类的内部创建一个当前类型的属性并赋值---在类的内部得到了当前类的一个对象
    //将变量私有化,让外界无法访问,给变量用static修饰让它成为全局的访问点
     private static SingleInstance1 singleInstance = null;    
    //1.将构造方法私有化
    private  SingleInstance1() {}    
    //3.使用公共的方法将变量提出去,并将方法设置成静态的
    public static SingleInstance1 getInstance() {
        if(singleInstance==null) {
        singleInstance = new SingleInstance1();
        }
          return singleInstance;
    }
       //4.单例的功能区
    int num;

    }
public class Demo5 {
    public static void main(String[] args) {
        SingleInstance singleInstance1=SingleInstance.getInstance();
        SingleInstance singleInstance2=SingleInstance.getInstance();
        System.out.println(singleInstance1==singleInstance2);  //true,说明获取到的是同一个对象    
        //实例:完成的功能:将A类中的num1值传给B类对象的num2        
        A a=new A();
        a.num1=4;
        B b = new B();            
//        //直接赋值,一般类的成员变量是私有的,所有不推荐
//        b.num2 = a.num1;
//        
//        //通过传参间接赋值
//        b.test(a);
//        //通过单例实现传值
        
        a.ceshi();
        b.ceshi2();
    }
}

//测试单例的功能
class A{
    int num1;
    public void ceshi() {
        SingleInstance1 singleInstance= SingleInstance1.getInstance();
        singleInstance.num=num1;        
    }
}

class B{
    int num2;
    //通过传参赋值
    public void test(A a) {
        num2=a.num1;    
    }    
    public void ceshi2() {
        SingleInstance1 singleInstance = SingleInstance1.getInstance();
        num2 = singleInstance.num;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值