//饿汉式 提前生成了单例对象
class Singleton{
    private static final Singleton instance=new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return instance;
    }

}

//懒汉式 调用的时候才会生成对象
class Singleton11
{
    private static Singleton11 instance;
    private Singleton11(){}
    
    public static Singleton11 getInstance(){
        if (instance==null)
        {
            instance=new Singleton11();
        }
        return instance;
    }
}

//多例模式
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 color;
    private Color(String color){
        this.color=color;
    }

    public static Color getInstance(String color){
        switch (color)
        {
        case "红色": return Red;
        case "绿色": return Green;
        case "蓝色": return Blue;
        default: return null;
        
        }
    }

    public String print(){
        return this.color;
    }
}


public class TestSingleton{
    public static void main(String[] args){
        Singleton A=Singleton.getInstance();
        Singleton B=Singleton.getInstance();
        System.out.println(A==B);

        Singleton11 A11=Singleton11.getInstance();
        Singleton11 B11=Singleton11.getInstance();
        System.out.println(A11==B11);

        Color red=Color.getInstance("红色");
        Color green=Color.getInstance("绿色");
        Color blue=Color.getInstance("蓝色");

        System.out.println(red.print());
        System.out.println(green.print());
        System.out.println(blue.print());
    }
}

 

多线程的情况:

class Singleton{
    private static volatile Singleton instance=null;  //直接操作主内存 比操作副本效果好
    private Singleton(){
        System.out.println(Thread.currentThread().getName()+"******实例化Singleton******");
    }
    public static Singleton getInstance(){
        if (instance==null){
            synchronized (Singleton.class){  //此处同步的是new Singleton() 提升多线程效率
                if (instance==null){         //此处的判断 对应上面的if (instance==null) 多个线程进来
                    instance=new Singleton();
                }
            }
        }
        return instance;
    }
    public void print(){
        System.out.println("wwww.mldn.com");
    }
}

public class SingleInstance {
    public static void main(String[] args) {
//        Singleton s=Singleton.getInstance();
//        s.print();
//        Singleton ss=Singleton.getInstance();
//        ss.print();
//        System.out.println(s==ss);
         for (int i=0;i<3;i++){
             new Thread(()-> System.out.println(Singleton.getInstance()),"单例"+i).start();
         }
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
  • 2021-09-17
  • 2021-11-25
  • 2022-12-23
猜你喜欢
  • 2021-08-27
  • 2022-01-08
  • 2022-12-23
  • 2022-02-21
  • 2021-04-11
  • 2021-05-02
  • 2021-07-24
相关资源
相似解决方案