饿汉式:
用java实现如下:
class Single
{
private String name="zhang san";
private int num=20;
private static Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
public void show()
{
System.out.println("name="+name+" "+"num="+num);
}
}
class SingleDemo
{
public static void main(String[] args)
{
Single s = Single.getInstance();
s.show();
}
}
用c++实现如下
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
int i;
string name;
static Student * s;
Student();
public :
static Student* getStudent();
void show();
};
Student * Student :: s = new Student();
Student :: Student(){}
Student* Student :: getStudent()
{
//Student* s = new Student();
s->name="zhangsan";
return s;
}
void Student :: show()
{
cout<<s->name;
}
int main()
{
//Student *s=new Student();
Student *s=Student::getStudent();
s->show();
return 0;
}
懒汉式:
c++实现如下:
#include <iostream> #include <string> using namespace std; class Student { private: int i; string name; static Student * s; Student(); public : static Student* getStudent(); void show(); }; Student * Student :: s = NULL; Student :: Student(){} Student* Student :: getStudent() { if(s==NULL) s = new Student(); s->name="zhangsan"; return s; } void Student :: show() { cout<<s->name; } int main() { //Student *s=new Student(); Student *s=Student::getStudent(); s->show(); return 0; } java实现如下:
class Student { private static Student s = null; private Student(){}; public Student getInstance() { if(s==null) { synchronized(Student.class) { if(s==null) { s = new Student(); } } } return s; } }