您的位置:首页 > 其它

单态设计模式--一个类只能创建一个实例(对象)

2011-11-06 22:27 232 查看
class Person

{

static Person p = new Person(); // 由于此声明在类内部,可以使用 new Person() 来创建新对象。声明为static,表明此类只能创建一个对象

String name;

int age;

private Person() 构造函数声明为private,类外部不可以用 new Person() 来创建新的对象

{

}

static Person getIntance() //此方法返回一个Person对象,用于外部类创建Person对象,声明为static则外部可用Person.getIntance()来构建对象

{

return p;

}

}

class Leason32

{

public static void main(String[] args)

{

//Person p1 = new Person();

Person p1 = Person.getIntance(); //构建Person对象实例

p1.name = "ye";

p1.age = 12;

Person p2 = Person.getIntance(); //再次构建Person对象实例

System.out.println(p2.name+p2.age); //取出p2实例的成员数据,因构建函数没有做任何动作,name=null,age=0,但此时输出为ye12,因Person只能构建一次,p2不能完成动作

}

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