一:(⊙_⊙;)单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。
二:单例模式的要点有三个:
1 某个类只能有一个实例;
2 是它必须自行创建这个实例;
3 是它必须自行向整个系统提供这个实例。
三:类图
四:
//“懒汉式”:
public class Singleton{
//静态成员记录唯一实例
private static Singleton uniqueInstance;
//把构造器申明为私有的,只有自己类才能实例化
private Singleton(){
}
//入口处
public static Singleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new Singleton();
}
return uniqueInstance;
}
}
线程不安全! 解决办法:使用同步机制
class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
//Singleton.class 作为锁,对象必须是单一的,根据反射可知返回的为Singleton类的对象
synchronized(Singleton.class){
if(instance == null){
instance=new Singleton();
}
}
return instance;
}
}
public class TestSingleton{
public static void main(String[] args){
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
System.out.println(s1==s2);
}
}
实验:提示:学生的学号生成方案,是在学生注册后,通过录入学生的基本信息,包括入学学年、学院、专业、班级等信息后,保存相应的资料后自动生成的。学号生成器的业务算法为:
入学学年(2位)+学院代码(2位)+专业代码(2位)+班级代码(2位)+序号(2位)
//Client.java
public class Client {
public static void main(String[] args) {
Student.getClient().setStudentNo("2015","计算机学院","软件工程","二班","01");
System.out.println(Student.getClient().getStuNo());
}
}
//Student.java
public class Student {
private static Student client=null;
private String studentno;
private String xn;
private String xy;
private String zy;
private String bj;
private String xh;
private Student(){};
//获取单一实例
int i=1;
public synchronized static Student getClient(){
if(client==null){
client=new Student();
}
return client;
}
public void setStudentNo(String xn,String xy,String zy,String bj,String xh){
this.xn=xn;
this.xy=xy;
this.zy=zy;
this.bj=bj;
this.xh=xh;
}
public String getStuNo(){
//分配原则
//入学学年(2位)+学院代码(2位)+专业代码(2位)+班级代码(2位)+序号(2位)
if(xn=="2015")
xn="15";
if(xy=="计算机学院")
xy="10";
if(zy=="软件工程")
zy="11";
if(bj=="二班")
bj="02";
studentno=xn+xy+zy+bj+xh;
return studentno;
}