Java单例设计和多例设计

单例设计模式:主要是一种控制实例化对象产生个数的设计操作,其中包含懒汉式和饿汉式两种方式; 单例和多例必须是构造方法私有化
单例模式(饿汉式):
class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){};//构造参数私有化
public static Singleton getInstance(){
return INSTANCE;
}
public void print(){
System.out.println(“单例模式打印”);
}
}
public class JavaDemo{
public static void main(String args[]){
Singleton instance = null;
instance = Singleton.getInstance();
instance.print();
}
}

单例模式(懒汉式):
       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("单例模式打印");
              }
       }
       public class JavaDemo{
               public static void main(String args[]){
               Singleton instance = null;
               instance = Singleton.getInstance();
               instance.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 static Color getInstance (String color){
switch(color){
case “red”: return RED;
case “green”: return GREEN;
case “blue”: return BLUE;
default:return null;
}
}
public String toString(){
return this.title;
}
}
public class JavaDemo{
public static void main(String args[]){
Color c= Color.getInstance(“green”);
System.out.println(c);
}
}

猜你喜欢

转载自blog.csdn.net/qq_41332396/article/details/81604470