您的位置:首页 > 其它

单例模式 singleton;

2017-01-07 09:19 471 查看
单例模式 singleton——一个人只能养一只猫


class Cat
{
String name;

//通过给构造方法加上private,使得只能在Cat类内部生成Cat对象
private Cat(String name)
{
this.name = name;
}

//我只生成一个猫对象名叫旺财,所以也就是单例
static Cat c = new Cat("旺财");

//通过加上static使得可以通过类名来直接调用这个方法,得到Cat对象
static Cat getCat()
{
return c;
}
}


public class Person
{
String name;
Cat c;

Person(String name)
{
this.name = name;
}

public String toString()
{
return name+"养了一只猫名叫"+c.name;
}

public static void main(String[] args)
{
Person father = new Person("张三");
father.c = Cat.getCat();

//养第二只猫出现错误,因为这是不允许的,Cat的构造方法是private的,所以在Cat类外访问不到其构造方法,新生成不了对象
//Cat a = new Cat("旺丁");

System.out.println(father);
}

}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息