Created
June 16, 2013 07:06
-
-
Save kingsamchen/5791218 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// only a single object allowed | |
struct PrintJob | |
{ | |
PrintJob(const string& name) : Name(name) | |
{ | |
} | |
string Name; | |
}; | |
class Printer | |
{ | |
public: | |
static Printer& Instance(); | |
void SubmitJob(const PrintJob& job) const; | |
private: | |
Printer() | |
{} | |
Printer(const Printer& other); | |
}; | |
Printer& Printer::Instance() | |
{ | |
static Printer printer; | |
return printer; | |
} | |
void Printer::SubmitJob(const PrintJob& job) const | |
{ | |
cout<<"submiting job now..."<<endl; | |
cout<<"job name: "<<job.Name<<endl; | |
cout<<"submitted"<<endl; | |
} | |
// alow a specific number of objects | |
class Printer | |
{ | |
public: | |
~Printer(); | |
static Printer* Instance(); | |
static Printer* Instance(const Printer& other); | |
void SubmitJob(const PrintJob& job) const; | |
private: | |
Printer(); | |
Printer(const Printer& other); | |
private: | |
static size_t _numObj; | |
enum {MAX_NUM_OF_OBJ_ALLOWED = 2}; | |
}; | |
Printer::Printer() | |
{ | |
++_numObj; | |
} | |
Printer::Printer(const Printer& other) | |
{ | |
++_numObj; | |
} | |
Printer::~Printer() | |
{ | |
--_numObj; | |
} | |
Printer* Printer::Instance() | |
{ | |
if (_numObj >= MAX_NUM_OF_OBJ_ALLOWED) | |
{ | |
return nullptr; | |
} | |
return new Printer; | |
} | |
Printer* Printer::Instance(const Printer& other) | |
{ | |
if (_numObj >= MAX_NUM_OF_OBJ_ALLOWED) | |
{ | |
return nullptr; | |
} | |
return new Printer(other); | |
} | |
void Printer::SubmitJob(const PrintJob& job) const | |
{ | |
cout<<"submiting job now..."<<endl; | |
cout<<"job name: "<<job.Name<<endl; | |
cout<<"submitted"<<endl; | |
} | |
int main() | |
{ | |
//Printer::Instance().SubmitJob(PrintJob("CLRS.txt")); | |
unique_ptr<Printer> p1(Printer::Instance()); | |
unique_ptr<Printer> p2(Printer::Instance()); | |
p1->SubmitJob(PrintJob("CLRS")); | |
p2->SubmitJob(PrintJob("TAOCP")); | |
Printer* p3 = Printer::Instance(); | |
if (p3 == nullptr) | |
{ | |
cout<<"reach the maximum number of objects"<<endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment