单例模式三要素
- 构造方法私有化
- 静态属性指向实例
- public static的 getInstance方法,返回第二步的静态属性
饿汉式单例模式
GiantDragon 应该只有一只,通过私有化其构造方法,使得外部无法通过new 得到新的实例。
GiantDragon 提供了一个public static的getInstance方法,外部调用者通过该方法获取12行定义的对象,而且每一次都是获取同一个对象。 从而达到单例的目的。
这种单例模式又叫做饿汉式单例模式,无论如何都会创建一个实例
package charactor;
public class GiantDragon {
//私有化构造方法使得该类无法在外部通过new 进行实例化
private GiantDragon(){
}
//准备一个类属性,指向一个实例化对象。 因为是类属性,所以只有一个
private static GiantDragon instance = new GiantDragon();
//public static 方法,提供给调用者获取12行定义的对象
public static GiantDragon getInstance(){
return instance;
}
}
懒汉式单例模式
懒汉式单例模式与饿汉式单例模式不同,只有在调用getInstance的时候,才会创建实例
package charactor;
public class GiantDragon {
//私有化构造方法使得该类无法在外部通过new 进行实例化
private GiantDragon(){
}
//准备一个类属性,用于指向一个实例化对象,但是暂时指向null
private static GiantDragon instance;
//public static 方法,返回实例对象
public static GiantDragon getInstance(){
//第一次访问的时候,发现instance没有指向任何对象,这时实例化一个对象
if(null==instance){
instance = new GiantDragon();
}
//返回 instance指向的对象
return instance;
}
}
然后我遇到了一个问题
public class Hero {
private String name;
private float hp;
private float armor;
private int moveSpeed;
private Hero(String name,float hp) {
this.name=name;
this.hp=hp;
System.out.println(this.name+this.hp);
}
private Hero(String name,float hp,float armor,int moveSpeed) {
this.name=name;
this.hp=hp;
this.armor=armor;
this.moveSpeed=moveSpeed;
System.out.println(this.name+this.hp+this.armor+this.moveSpeed);
}
private static Hero instance=new Hero( “虞姬”, 50);
private static Hero instance1=new Hero(“墨子”,45,48,98);
public static Hero getInstance1() {
return instance1;
}
public static Hero getInstance() {
return instance;
}
}
public class TestHero {
public static void main(String args[]) {
Hero m=Hero.getInstance1();
}
}
为什么在TestHero()调用第二个构造函数时第一个构造函数也会运行?
运行第二个Instance1()时
虞姬 50
墨子 45 48 98