---------------------- android培训、java培训、期待与您交流! ----------------------
/*
* 单例设计模式:
* 要设计一个单例的类,按照如下三步即可:
* 这三步怎么用代码实现呢?
1,将构造函数私有化。private
2,在类中创建一个本类对象。private static
3,提供一个方法可以获取到该对象。public static。方法是静态,让它可以通过类名来调用。
* */
public class SingleDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu1 = Student.getStudent();
Student stu2 = Student.getStudent();
System.out.println(stu1 == stu2);//打印结果显示:
//创建的两个Student对象stu1、stu2,实际上是同一个对象。
stu1.setAge(20);//Student类的其他set和get方法可以像普通类一样写。
System.out.println(stu1.getAge());
}
}
/*要让外部程序操作的始终是一个对象:
* 加上私有构造方法,让外部程序只能通过类名来获取现成的对象。
* 注意以上这句话:私有构造方法、现成的对象(定义在类中)、获取(public 的get方法)。
* 代码: private static Student s = new Student();
private Student(){}
public static Student getStudent(){
return s;
}
以上的三段代码,让Student类具备了单例的特性,这样,外部程序就不能再new 对象了。
而能操作的对象只能是s。
*/
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;
}
}
-----------------------------
/*
* 单例设计模式方式二。
* --------------
* 第一种单例设计模式的写法:(饿汉式:先初始化对象)
* 1,创建一个私有并静态的本类对象。
2,建立一个私有的空参构造函数。
3,建立一个公有并静态的返回本类对象的方法。
代码实现如下:
class Single{
private static Single s = new Single();
private Single(){}
public static Single getInstance(){
return s;
}
---------------
第二种单例设计模式的写法:(懒汉式。对象是被方法调用时才初始化,也叫对象的延时加载。)
代码实现:
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s=null)
s = new Single();
return s;
}
synchronized改进:
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s=null){
synchronized(Single.class)
{
if(s==null)
s = new Single();
}
}
return s;
}
}
----
面试的考点:饿汉式和懒汉式,以及synchronized的锁问题,多线程相关。
* */
---------------------- android培训、java培训、期待与您交流! ----------------------
详情请查看: