java设计模式

设计模式

单例模式

在程序运行过程中,同一个类只出现一个对象

目的:减少内存的消耗

如何查看对象同一个对象: 看内存地址。如果内存地址一样就是一个对象

普通写法

class People {
    private static People people = null;
    //1.对构造方法私有化
    private People () {
        
    }
    //2.写一个静态方法  使用类名直接调用的   不能使用对象来调用的  因为私有化构造方法了
    public static  People getInstance () {
        if (people == null) {
            people = new People();
        }

        return people;
    }

}
public class Demo1 {
    public static void main(String[] args) {
        //当一new就会新建对象,创建唯一的对象,对当前类的无参构造方法加private修饰
        People people = People.getInstance();
        People people1 = People.getInstance();
        System.out.println(people);
        System.out.println(people1);
    }
}

加上了线程安全

class SingleDog {
    private static SingleDog singleDog;
    private SingleDog() {

    }
    public static synchronized SingleDog getInstance() {
        synchronized (SingleDog.class) {
            if (singleDog == null) {


                //线程1进来了还没有new 呢,结果线程2抢到执行权利的
                //结果线程2 发现singleDog  是空的    new

                singleDog = new SingleDog();
            }
        }

        return singleDog;
    }
}
//在两个线程中去创建单例对象的时候  如果发现对象内存不一样,就证明线程不安全
class Mythread1 implements Runnable {
    @Override
    public void run() {
        SingleDog instance = SingleDog.getInstance();
        System.out.println(instance);//对象的内存地址
    }
}
class Mythread2 implements Runnable {
    @Override
    public void run() {
        SingleDog instance = SingleDog.getInstance();
        System.out.println(instance);//对象的内存地址
    }
}
public class Demo2 {
    public static void main(String[] args) {
        new Thread(new Mythread1()).start();
        new Thread(new Mythread2()).start();
    }
}

懒汉式写法

class People {
    private static People people = null;
    //1.对构造方法私有化
    private People () {
        
    }
    //2.写一个静态方法  使用类名直接调用的   不能使用对象来调用的  因为私有化构造方法了
    public static  People getInstance () {
        if (people == null) {
            people = new People();
        }

        return people;
    }

}
public class Demo1 {
    public static void main(String[] args) {
        //当一new就会新建对象,创建唯一的对象,对当前类的无参构造方法加private修饰
        People people = People.getInstance();
        People people1 = People.getInstance();
        System.out.println(people);
        System.out.println(people1);

    }
}

饿汉式的写法

class SingleCat {
    private static final SingleCat singleCat = new SingleCat();
    private SingleCat() {

    }
    public static SingleCat getInstance() {
        return singleCat;
    }

}
public class Demo3 {
    public static void main(String[] args) {

    }
}

懒汉式: 线程不安全

饿汉式: 线程安全的

效率高: 饿汉式的效率高,因为没有加锁

性能来说: 饿汉式类一加载就必须加载对象,但是懒汉式的当需要的时候才去new

开发中用懒汉

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值