-
阿⾥总裁到⼴州,北京,上海访问 总裁属性:姓名,年龄,性别 要求:使⽤单例实现
//阿⾥总裁到⼴州,北京,上海访问 总裁属性:姓名,年龄,性别 要求:使⽤单例实现 public class Work1 { public static void main(String[] args) { Person p = Person.getP(); p.setAge(50); p.setSex("男"); p.setName("马云"); p.visit("广州"); p.visit("北京"); p.visit("上海"); } static class Person{ private static Person p = null; String name; int age; String sex; private Person(){ } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public static Person getP(){ synchronized (Person.class){ if(p==null){ p=new Person(); } } return p; } public void visit(String name){ System.out.println(getP()+"访问"+name); } } }
设计模式-单例模式懒汉式
最新推荐文章于 2024-05-04 16:10:41 发布