欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java创建单例对象,java创建对象,单例是值类只有一个实例,

来源: javaer 分享于  点击 26019 次 点评:16

java创建单例对象,java创建对象,单例是值类只有一个实例,


单例是值类只有一个实例,如下是java中创建单例的代码:

/** * MySingleton.java * * @author byrx.net */public class MySingleton {    //the static singleton object    private static MySingleton theObject;    /**     * private constructor     */    private MySingleton() {    }    /**     * 检查静态字段是否为null,若为null则创建实例,否则直接返回实例     *     * @return the singleton object     */    public static MySingleton createMySingleton() {        if (theObject == null)            theObject = new MySingleton();        return theObject;    }}

不管调用多少次createMySingleton()方法,返回的都是同一个实例:

/** * Main.java * * @author byrx.net */public class Main {    /**     * Gets references to the singleton     * instance and checks if they point to the same object.     */    public void createSingleton() {        MySingleton ms1 = MySingleton.createMySingleton();        MySingleton ms2 = MySingleton.createMySingleton();        System.out.println( ms1 == ms2 );    }    /**     * 启动程序     *     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().createSingleton();    }}
相关栏目:

用户点评