方法一、
对象唯一性一般能想到工厂模式,单例模式,我们这里介绍一下举例懒汉法。
单例模式详解
- package com.liuyanzhao;
- class Student {
- private String name;
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- private Student() {
- }
- private static Student s = new Student();
- public static Student getInstance() {
- return s;
- }
- }
- public class Test {
- public static void main(String[] args) {
- Student s1 = Student.getInstance();
- Student s2 = Student.getInstance();
- s1.setName("Tom");
- s2.setName("Jerry");
- System.out.println(s1.getName());//Jerry
- System.out.println(s2.getName());//Jerry
- }
- }
新建的两个对象s1,s2其实是一个对象
方法二、
通过计数器统计来创建对象
- package com.liuyanzhao;
- class Teacher {
- static int i=0;
- private String name;
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- private Teacher() {
- }
- public static Teacher newTeacher() {
- Teacher.i++;
- if(Teacher.i>1){
- return null;
- }
- return new Teacher();
- }
- }
- public class Test1 {
- public static void main(String[] args) {
- Teacher t = Teacher.newTeacher();
- Teacher t1 = Teacher.newTeacher();
- t.setName("Tom");
- //t1.setName("Jerry");
- System.out.println(t.getName());
- //System.out.println(t1.getName());
- }
- }
如上 只能创建一个对象,否则会报错。
本文地址:http://liuyanzhao.com/3328.html
转载请注明
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏