您的位置:首页 > 职场人生

【黑马程序员】java基础_单例设计模式

2014-06-10 15:29 337 查看
------- android培训java培训、期待与您交流! ----------

什么是设计模式?设计模式就是 解决某一类问题最有效的方法。

java的设计模式一共有23种

常见的如单例设计模式、模板设计模式、装饰设计模式等等,其中单例设计模式又分为懒汉式和饿汉式。

单例设计模式:保证对象唯一。

1、为了避免其他程序过多建立该类对象。先禁止其他程序建立该类对象。

2、还为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象。

3、为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式

代码步骤:

1、将构造函数私有化

2、在类中创建一个本类对象,并静态私有化

3、提供一个方法获取到该对象
class Student
{
private String name;
private int age;

public void setInformation(String name,int age)
{
this.name = name;
this.age = age;
}

public String getName()
{
return name;
}

public int getAge()
{
return age;
}

//懒汉式(延时加载):什么时候调用,什么时候进内存
private static Student s = null; //饿汉式:private static final Student s = new Student();
private Student(){}
public static Student getInstance()
{
if(s == null) //饿汉式:不用
{ //饿汉式:不用
synchronized(Student.class) //饿汉式:不用
{ //饿汉式:不用
if(s == null) //饿汉式:不用
s = new Student(); //饿汉式:不用
} //饿汉式:不用
}
return s;
}
}

public class SingleDemo
{
public static void main(String[] args)
{
Student s1 = Student.getInstance();
Student s2 = Student.getInstance();
s1.setInformation("张三",21);
System.out.println("S1:"+s1.getName()+"\t"+s1.getAge());
System.out.println("S2:"+s2.getName()+"\t"+s2.getAge());
}
}

PS:一般情况下最好使用饿汉式,因为多人调用时懒汉式容易出错

PS2:解决懒汉式问题,用synchronized(锁)进行双重判断
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: