java设计模式单件模式_Head First设计模式(5):单件模式

更多的可以参考我的博客,也在陆续更新ing

http://www.hspweb.cn/

单件模式确保一个类只有一个实例,并提供一个全局访点。

例子:学生的学号生成方案,是在学生注册后,通过录入学生的基本信息,包括入学学年、学院、专业、班级等信息后,保存相应的资料后自动生成的。学号生成器的业务算法为:

入学学年(2位)+学院代码(2位)+专业代码(2位)+班级代码(2位)+序号(2位)

1.目录

6e826dd9b4fc

image

2.student.java

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Locale;

public class Student {

private static Student client=null;

private Student() {}

public synchronized static Student getClient() {

if(client==null) {

try {

client=new Student();

}catch(Exception e) {

e.printStackTrace();

}

}

return client;

}

public String getStuNo() {

String yearLast = new SimpleDateFormat("yy",Locale.CHINESE).format(Calendar.getInstance().getTime());

String college="02";

String professional="02";

String classNum="1024";

String ramdon=String.valueOf((int)(Math.random()*90+10));

return yearLast+college+professional+classNum+ramdon;

}

}

3.test.java

public class test {

public static void main(String[] args) {

Student student = Student.getClient();

System.out.println("生成的学生学号是:"+student.getStuNo());

}

}

4.类图

6e826dd9b4fc

image

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值