设计模式总结

一、单例模式

该模式的特点是类加载时没有生成单例,只有当第一次调用 getlnstance 方法时才去创建这个单例。单例模式有如下特点:

  1. 单例类只有一个实例对象;
  2. 该单例对象必须由单例类自行创建;
  3. 单例类对外提供一个访问该单例的全局访问点

代码如下:

1、懒汉式

public class Person{
    private static volatile Person instance = null;
    private Person(){};    //私有的空参构造器,避免外部调用
    
    public synchronized Person getInstance(){
        if(instance == null){
            return new Person();
        }else{
        
            return instance;
        }
    } 
}

2、饿汉式

public class Person{
   private static final Person instance = new Person();
   private Person(){
        
    }
    public Person getInstance(){
        return instance;
    }
}

例1:用单例模式模拟产生猪八戒对象

//饿汉式
public class Zhubajie{
    private static final String name = "zhubajie";
    private static final String otherName = "天蓬元帅";
    private zhubajie(){};
    private static final Zhubajie instance = new Zhubajie(); 
    public Zhubajie getInstance(){
         return instance;   
    }
    public String getName(){
        return name;
    }
    public String getOtherName(){
        return otherName;
    }
}
//懒汉式
public class Zhubajie{
    private static final String name = "zhubajie";
    private static final String otherName = "天蓬元帅";
    private static volatile Zhubajie = null;

    private Zhubajie(){};
    public Zhubajie getInstance(){
        if(instance == null){
            return new Zhubajie();
        }else{
            return instance;
        }
    }
    public String getName(){
        return name;
    }
    public String getOtherName(){
        return otherName;
    }
    



}

未完待续。。。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值