1.勤快式(饿汉式)
欢迎大家提出意见和见解(后面的注释多一点)
Integer类
//勤快的
public class MyInteger {
private final static int LENGTH=11;
private int num;
private MyInteger(int n){
this.num=n;
}
//分配空间
private static MyInteger[] m = new MyInteger[LENGTH];
//给数组赋值 装箱,第一次使用这个类的时候执行,执行一次,优先执行
//普通语句块,new一个对象执行一次
static{
for(int i=0;i<m.length;i++){
m[i]=new MyInteger(i);
}
}
public static MyInteger valueOf(int num){
//判断这个数是不是在装好的箱子中
if((num>=0)&&(num<m.length)){
return m[num];
}
return new MyInteger(num);
}
@Override
public String toString(){
return "num"+num;
}
}
测试类
public class test {
public static void main(String[] args){
MyInteger a = MyInteger.valueOf(10);
MyInteger b = MyInteger.valueOf(10);
System.out.println(a==b);
System.out.println(a+"..."+b);
}
}
2.比较懒(懒汉式)
Integer类
//用懒汉式实现装箱(比较懒后面还有更懒的方式)
//懒汉式
public class MyIntegerLazy {
//声明一个常量,常量大写
private final static int LENGTH=11;
private int num;
private MyIntegerLazy(int n){
this.num=n;
}
//知识声明了一个数组
private static MyIntegerLazy[] m =null;
public static MyIntegerLazy valueOf(int num){
//数组没有分配空间就给数组分配空间
if(m ==null){
m=new MyIntegerLazy[LENGTH];
//语句块装箱(对象是否存在)!!!!m[num]==null m[num]=new MyInteger(num)需要哪个生产那个
for(int i=0;i<m.length;i++){
m[i]=new MyIntegerLazy(i);
}
}
//if(m[0]=null).....如果在这里创建对象需要判断第一个对象是否为空
if((num>=0)&&(num<m.length)){
return m[num];
}
return new MyIntegerLazy(num);
}
@Override
public String toString(){
return "num"+num;
}
}
测试类
//比较懒
public class Mytest {
public static void main(String[] args) {
MyIntegerLazy a =MyIntegerLazy.valueOf(12);
MyIntegerLazy b =MyIntegerLazy.valueOf(12);
System.out.println(a==b);
System.out.println(a+"..."+b);
}
}
3.超级懒(懒汉式)
Integer类
public class MyIntegerVeryLazy {
//超级懒
//定义常量(不可变)
private final static int LENGTH=11;
//用于后面重写toString测试用
private int num;
//有参的传参
private MyIntegerVeryLazy(int n){
this.num=n;
}
//超级懒数组空间都不开辟
private static MyIntegerVeryLazy[] m =null;
//公共的访问方法
public static MyIntegerVeryLazy valueOf(int num){
//先判断对象是否有存放的空间,若没有则创建空间
if(m==null){
m = new MyIntegerVeryLazy[LENGTH];
}
//创建完空间后判断空间内是否有对象,若没有对象则利用循环创建对象
if(m[0]==null){
for(int i=0;i<m.length;i++){
m[i]=new MyIntegerVeryLazy(i);
}
}
//num这个范围内创建的对象用的是一个对象
if((num>=0)&&(num<m.length)){
//返回当前对象
return m[num];
}
//也就是else(不在这个范围内)新创建对象
return new MyIntegerVeryLazy(num);
}
//重写toString方法用于测试
@Override
public String toString(){
return "num"+num;
}
}
测试类
public class VeryLazyTest {
public static void main(String[] args) {
//输入0-10的数会显示true,否则为false
MyIntegerVeryLazy a =MyIntegerVeryLazy.valueOf(8);
MyIntegerVeryLazy b =MyIntegerVeryLazy.valueOf(8);
System.out.println(a==b);
System.out.println(a);
System.out.println(b);
//这样输出更好看,为了更却切a和b不是两个null可以把重写的toString方法去掉
}
}