JAVA面试之设计模式

本文深入探讨了Java面试中的设计模式,包括单例模式的懒汉和饿汉实现,以及工厂模式的简单工厂、工厂方法和抽象工厂模式的应用和特点。通过这些模式,我们可以实现对象的灵活创建,提高代码的可维护性和可扩展性。
摘要由CSDN通过智能技术生成

一.单例模式

1.懒汉模式

只有在第一次调用的时候会实例化对象

public class Singleton1{
    private static Singleton1 instance = null;
    
    //构造方法
    private Singleton1(){

    }
    /**
    *单线程模式
    */
    public static Singleton1 getInstanceA(){
        
        if(instace = null){
            instance = new Singleton1();
        }
        retrun instance
    }
     /**
     * 多线程环境 我们加个关键字,让方法变成同步方法就好了
     */
    public static synchronized Singleton1 getInstanceB() {
        if (instance == null) {
            instance = new Singleton1();
        }
        return instance;
    }

    /**
     * 双重检查加锁(
     */
    public static Singleton1 getInstanceC() {
        // 先判断实例是否存在,若不存在再对类对象进行加锁处理
        if (instance == null) {
            synchronized (Singleton1.class) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
        }
        return instance;
    }


}

2.饿汉模式

饿汉式单例类:在类初始化时,已经自行实例化。

public class Singleton2{
    private static Singleton2 instance = new Singleton2();

     private Singleton2() {
    }
    public static Singleton2 getInstance(){
        returin instance;

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值