シングルカラムモード [Hungry Man Style と Lazy Man Style]
シングルトン パターンは、1 つのオブジェクトとそのオブジェクトを取得するメソッドのみを提供するクラスです。
シングルトン パターンには次の 2 種類があります。
- お腹を空かせた中華風
- 怠け者のスタイル
1. お腹を空かせた中華風
- プライベートコンストラクター
- クラス内にオブジェクトを作成する
- このクラスのオブジェクトにアクセスするための静的メソッドを提供します。
package com.linghu.single;
/**
* 饿汉式
* @author 令狐荣豪
* @version 1.0
*/
public class SingleTon01 {
public static void main(String[] args) {
// Girlfriend instance = Girlfriend.getInstance();
// System.out.println(instance);
//饿汉式
System.out.println(Girlfriend.n);//访问静态属性时,类的对象还是会被初始化创建,这就浪费了!
}
}
class Girlfriend{
private String name;
public static int n=100;
private static Girlfriend gf=new Girlfriend("小红");
private Girlfriend(String name) {
System.out.println("构造器。。。");
this.name = name;
}
public static Girlfriend getInstance(){
return gf;
}
@Override
public String toString() {
return "Girlfriend{" +
"name='" + name + '\'' +
'}';
}
}
2. 怠け者のスタイル
package com.linghu.single;
/**
* 懒汉式
* @author 令狐荣豪
* @version 1.0
*/
public class SingleTon02 {
public static void main(String[] args) {
//访问静态属性的时候,对象不会被创建,不会浪费,需要的时候才会初始化创建对象
System.out.println(Cat.n);
// Cat instance = Cat.getInstance();
// System.out.println(instance);
}
}
class Cat{
private String name;
public static int n=100;
private static Cat cat;
private Cat(String name) {
System.out.println("构造器调用...");
this.name = name;
}
public static Cat getInstance(){
if (cat==null){
cat=new Cat("喵喵");
}
return cat;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
3. まとめ
Hungry スタイルと Lazy スタイルではオブジェクトの作成タイミングが異なり、Hungry スタイルはクラスのロード時に作成され、Lazy スタイルはクラスの使用時に作成されます。