单例模式 回顾

来源:互联网 发布:美国亚马逊服务软件 编辑:程序博客网 时间:2024/06/07 18:13

单例模式:让一个类只能创建一个对象

设计模式:设计经验,是一套固定的设计代码的经验


步骤:

1. 首先让构造函数私有化

2.提供一套static修饰的函数 并且  返回一个对象


单例模式一共有两种方式表达:

1.饿模式

public class OOTest{    private OOTest(){}    private static OOTest oo = new OOTest();    public static OOTest   getOO(){//饿模式    return oo;}}

2.懒模式

public class OOTest{    private OOTest(){}    private static OOTest oo = null;    public static OOTest  getoo(){    if(oo = null)){        oo = new TestOO();    }else{            return oo;    }}}

如果 需要用他   初始化  就可以了

private OOTest ot = new  OOTest.getoo(); // 初始化实例对象



0 0
原创粉丝点击