设计模式之单例模式

题目

[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。

类图

Java

StudentNp

package com.gazikel;

public class StudentNo {
    private static volatile StudentNo instance = null;
    private String no;
    private StudentNo(){

    }

    public static StudentNo getInstance(){
        if (instance == null) {
            synchronized (StudentNo.class) {
                if (instance == null) {
                    System.out.println("第一次创建学号,分配新号码");
                    instance = new StudentNo();
                    instance.setStudentNo("123");
                }
            }

        } else {
            System.out.println("重复创建学号,获取旧号码");
        }
        return instance;
    }

    private void setStudentNo(String no) {
        this.no = no;
    }

    public String getStudentNo() {
        return this.no;
    }
}

Client

package com.gazikel;

public class Client {

    public static void main(String[] args) {
        StudentNo no1, no2;
        no1 = StudentNo.getInstance();
        no2 = StudentNo.getInstance();

        if (no1 == no2) {
            System.out.println("该同学学号唯一");
        } else {
            System.out.println("该同学学号不唯一");
        }
        // System.out.println("学号是否一致" + (no1 == no2));

        System.out.println("------------------");
        String str1, str2;
        str1 = no1.getStudentNo();
        str2 = no2.getStudentNo();
        System.out.println("第一次号码:" + str1);
        System.out.println("第而次号码:" + str2);
        System.out.println("内容是否相等:" + str1.equalsIgnoreCase(str2));
        System.out.println("是否相同对象:" + (str1 == str2));
    }
}

C++

main.cpp

#include<iostream>
#include<string>
using namespace std;

class StudentNo {
public:
	static StudentNo* getInstance() {
		if (instance == NULL)
		{
			instance = new StudentNo;
			instance->setStudentNo("20194077");
		}
		return instance;
	}

	string getStudentNo() {
		return this->no;
	}


private:
	static StudentNo *instance;
	string no;
	StudentNo() {}
	void setStudentNo(string no) {
		this->no = no;
	}

};

StudentNo * StudentNo::instance = NULL;

int main(void) {

	StudentNo* no1 = StudentNo::getInstance();
	StudentNo* no2 = StudentNo::getInstance();

	string str1, str2;
	str1 = no1->getStudentNo();
	str2 = no2->getStudentNo();
	cout << "第一次号码:" << str1 << endl;
	cout << "第二次号码:" << str2 << endl;

	if ((no1 == no2) && (str1 == str2))
	{
		cout << "每位学生有唯一学号" << endl;
	}
	else {
		cout << "每位学生学号不唯一" << endl;
	}
}
posted @ 2021-11-24 23:25  Gazikel  阅读(50)  评论(0编辑  收藏  举报