·-|单列模式(饿汉模式):
/**
* 单例模式(饿汉模式)
* @author 渣渣辉
*
*/
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}// 构造私有化
public static Singleton getInstance() {
return INSTANCE;
}
public void print() {
System.out.println("Hello World!");
}
}
public class SingletonDemo {
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
s.print();
}
}
·-|单列模式(懒汉模式):
/**
* 单列模式(懒汉模式)
*
* @author 渣渣辉
*
*/
class Singleton {
private static Singleton instance;
private Singleton() {
}// 构造私有化
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void print() {
System.out.println("Hello World!");
}
}
public class SingletonDemo01 {
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
s.print();
}
}
·-|多例模式:
/**
* 多例模式
*
* @author 渣渣辉
*
*/
class Sex {
private String title;
private static final Sex MALE = new Sex("男 ");
private static final Sex FEMALE = new Sex("女");
private Sex(String title) {
this.title = title;
}
public String toString() {
return this.title;
}
public static Sex getInstance(String str) {
switch (str) {
case "man":
return MALE;
case "women":
return FEMALE;
default:
return null;
}
}
}
public class MultitonDemo {
public static void main(String[] args) {
Sex sex = Sex.getInstance("man");
System.out.println(sex);
}
}
class Sex {
private String title;
private static final Sex MALE = new Sex("男");
private static final Sex FEMALE = new Sex("女");
public Sex(String title) {
this.title = title;
}
@Override
public String toString() {
return this.title;
}
public static Sex getInstance(String str) {
switch (str) {
case "man":
return MALE;
case "woman":
return FEMALE;
default:
return null;
}
}
}
public class Demo {
public static void main(String[] args) {
Sex sex=Sex.getInstance("man");
System.out.println(sex);
}
}