单例和多例的设计模式特点就是构造方法被私有化,外部无法直接用“new”实例化。只能通过调用类内部提供的静态方法取得实例。
单例设计模式:
饿汉式单例设计模式
class Singleton{
private Singleton(){}
//定义全局常量的时候直接实例化
private static final Singleton INSTANCE = new Singleton();
public static Singleton getSingleton(){
return INSTANCE;
}
public void print(){
System.out.println("输出");
}
}
public class Test {
public static void main(String[] args) {
Singleton s = Singleton.getSingleton();
s.print();
}
}
懒汉式单例设计模式
class Singleton{
private Singleton(){}
private static Singleton INSTANCE =null;
public static Singleton getSingleton(){
if(INSTANCE ==null){ //在调用的时候再实例化
INSTANCE = new Singleton();
}
return INSTANCE;
}
public void print(){
System.out.println("输出");
}
}
public class Test {
public static void main(String[] args) {
Singleton s = Singleton.getSingleton();
s.print();
}
}
饿汉单例设计模式:不管有没有调用,都已经实例化。
懒汉单例设计模式:当被调用的时候,再进行实例化。
多例设计模式
单例和多例的区别是,单例只提供一个实例化对象,而多例会存在多个实例化对象,例如性别只提供两个实例,星期只提供七个实例。
class Color {
private static final Color RED = new Color("红色") ;
private static final Color GREEN = new Color("绿色") ;
private static final Color BLUE = new Color("蓝色") ;
private String title ;
private Color(String title) {
this.title = title ;
}
public String toString() {
return this.title ;
}
public static Color getColor(String colors) {
switch (colors) {
case "red" : return RED ;
case "green" : return GREEN ;
case "blue" : return BLUE ;
default : return null ;
}
}
}
public class TestDemo {
public static void main(String args[]) {
Color red = Color.getColor("red") ;
System.out.println(red) ;
}
}