黑马程序员技术交流社区

标题: 单例设计模式 [打印本页]

作者: 史世锋    时间: 2015-9-13 19:43
标题: 单例设计模式
设计模式:解决某一类问题最行之有效的方法。
单例设计模式:解决一个类在内存中只存在一个对象。
想要保证对象唯一:
1.为了避免其他程序过多的建立该类对象,先进制其他程序建立该类对象
2.为了让其他程序访问到该类对象,只好在本类中定义一个对象
3.为了方便其他程序对该对象的访问,可以对外提供一些访问方式
代码体现:
1.将构造函数私有化
2.在类中创建一个本类对象
3.提供一个获取到该对象的方法
class Atm
{
        private int money = 10000;
        //创建一个本类对象,并私有化
        private static Atm atm = new Atm();
       
        //将构造函数私有化,其他程序将不能创建本类对象
        private Atm(){};
       
        //提供一个静态方法返回本类对象,以便被类名调用
        public static Atm getAtm()
        {
                return atm;
        }
        public void setMoney(int money)
        {
                this.money = this.money + money;
        }
        public int getMoney(int money)
        {
                this.money = this.money - money;
                return money;
        }
        public void searchMoney()
        {
                System.out.println("money=" + money);
        }
}
public static void main(String[] args)
        {
                Atm atm = Atm.getAtm();
                Atm atm1 = Atm.getAtm();
                atm.getMoney(1000);
                atm1.searchMoney();
                atm1.getMoney(653);
                atm.searchMoney();
        }   结果:
money=9000
money=8347
饿汉式和懒汉式:
package com.itheima;
//先初始化对象,称为饿汉式,开发会经常用饿汉式 ,因为安全
class Single
{
        private static Single s = new Single();
        private Single(){};
        public static Single getInstance()
        {
                return s;
        }
}
//需要时再初始化对象,称为懒汉式
//Single1进内存,对象还没有存在,只有调用了getInstance方法时,才会创建对象
//也称为对象的延时加载
class Single1
{
        private static Single1 s1 = null;
        private Single1(){};
        public static Single1 getInstance()
        {
                if(s1 == null)
                        s1 = new Single1();
                return s1;
        }
}
//安全的懒汉式,同步代码块
class Single2
{
        private static Single2 s2 = null;
        private Single2(){};
        public static Single2 getInstance()
        {
                if(s2 == null)
                {
                        synchronized (Single2.class)
                        {
                                if(s2 == null)
                                        s2 = new Single2();
                        }
                }
                       
                return s2;
        }
}












欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2