码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的单例设计模式举例

时间:2016-06-09 09:42:36      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

本例中通过将构造函数私有化的方式将实例化对象的代码放到类内部的静态函数中,从而实现单例设计模式。

class Singleton
{
    static Singleton instance = new Singleton();
    private Singleton()
    {

    }

    public static Singleton getInstance()
    {
        return Singleton.instance;
    }


    public void func()
    {
        System.out.println("Hi there, this is a singleton demo.");
    }
}

public class  Hello
{ 
    public static void main(String[] args) 
    { 
        Singleton ins_1 = Singleton.getInstance();
        Singleton ins_2 = Singleton.getInstance();
        Singleton ins_3 = Singleton.getInstance();


        ins_1.func();
        ins_2.func();
        ins_3.func();
    } 
}

 

Java中的单例设计模式举例

标签:

原文地址:http://www.cnblogs.com/kuillldan/p/5571989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!