单例设计模式(多例设计模式)主要是一种控制实例化对象产生个数的设计操作。核心为构造方法私有化。
1 单例设计
要求Singleton这个类只允许有一个实例化对象。那么此时我们首先应该控制的就是构造方法。因为所有新的实例化对象产生了,一定要调用构造方法。
范例:饿汉式
class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return Singleton.INSTANCE;
}
public void print(){
System.out.println("Singleton!");
}
}
public class JavaDemo{
public static void main(String[] args){
Singleton sin = Singleton.getInstance();
sin.print();
}
}
在很多情况下有些类是不需要重复产生对象的。对单例设计模式也分为两种:懒汉式和饿汉式。在系统加载就会自动提供类的实例化对象。懒汉式指在第一次使用的实例化对象。
class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(Singleton.instance == null){
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public void print(){
System.out.println("Singleton!");
}
}
public class JavaDemo{
public static void main(String[] args){
Singleton sin = Singleton.getInstance();
sin.print();
}
}
面试题:请编写一个Singleton程序,并说明其主要特点?
(1)代码如上,可以把懒汉式(后面需要考虑到线程同步问题)和饿汉式都写上;
(2)特点:构造方法私有化,类内部提供static方法获取实例化对象,这样不管外部如何操作永远都只有一个实例化对象提供。
2 多例设计
多例设计模式指的是可以保留多个实例化对象。
class Color{
private static final Color RED = new Color("red");
private static final Color GREEN = new Color("green");
private static final Color BLUE = new Color("blue");
private String title;
private Color(String title){
this.title = title;
}
public static Color getInstance(String color){
Color instance = null;
switch(color){
case "red": instance = RED;break;
case "green": instance = GREEN;break;
case "blue": instance = BLUE;break;
default: break;
}
return instance;
}
public void info(){
System.out.println(this.title);
}
}
public class JavaDemo{
public static void main(String[] args){
Color co = Color.getInstance("red");
co.info();
}
}