设计模式-饿汉式、懒汉式

来源:互联网 发布:淘宝微信福利群可信吗 编辑:程序博客网 时间:2024/05/29 08:35
  1. 单例设计模式:确保一个类中有且仅有一个实例并为他提供一个全局访问点。
    具体实现:
    1.将构造函数私有化。
    2.在类中创建一个本类对象。
    3.提供一个方法可以获取到该对象。
  2. 2.1饿汉式:Single类一进内存,就已经创建好了对象。
class Single{    private  Single(){}    private static Single s = new Single();    public static  Single getInstance(){        return s;    }}
  2.2懒汉式:会被延迟加载,对象是方法被调用时,才初始化。
class SingleDemo {      private static SingleDemo s = null;      private SingleDemo(){}      public static synchronized SingleDemo getInstance(){          if(s == null){              s = new SingleDemo();          }          return s;      }  }  

3.饿汉式单例

class SingletonDemo{    public static void main(String[] args) {        Student s1 = Student.getStudent();        s1.setAge(12);        Student s2 = Student.getStudent();        s2.setAge(30);        System.out.println(s1.getAge());        System.out.println(s2.getAge());    }}class Student{    private int age;    private static Student s = new Student();    private Student(){}    public static Student getStudent(){        return s;    }    public void setAge(int age){        this.age = age;    }    public int getAge(){        return age;    }}

4.懒汉式单例
懒汉式在单线程下懒汉式与饿汉式没有区别。但在多线程环境下,饿汉式没有问题,
懒汉式可能会产生多个实例。因此要使用线程同步(synchronized),保证在多线程环境下,不创建多个实例。

懒汉式 单线程

class Demo{    public static void main(String[] args) {          SingleDemo s1 = SingleDemo.getInstance();          SingleDemo s2 = SingleDemo.getInstance();          System.out.println(s1 == s2);         System.out.println(s1);         System.out.println(s2);     }  }class SingleDemo {      private static SingleDemo s = null;      private SingleDemo(){}      public static SingleDemo getInstance(){          if(s == null){              s = new SingleDemo();          }          return s;      }  }  

懒汉式 多线程

class SingletonDemo2{    public static void main(String[] args) {          RunDemo r1=new RunDemo();        RunDemo r2=new RunDemo();        Thread t1=new Thread(r1);        Thread t2=new Thread(r2);        t1.start();        t2.start();    }  }class RunDemo extends Thread{    public void run(){        System.out.println(SingleDemo.getInstance());    }}class SingleDemo {      private static SingleDemo s = null;      private SingleDemo(){}      public static synchronized SingleDemo getInstance(){          if(s == null){              s = new SingleDemo();          }          return s;      }  }  

懒汉式的目的是为了提高性能,synchronized却降低了性能.(开发过程尽量使用饿汉式)

0 0