Skip to content

Instantly share code, notes, and snippets.

@kingsamchen
Created June 16, 2013 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingsamchen/5791218 to your computer and use it in GitHub Desktop.
Save kingsamchen/5791218 to your computer and use it in GitHub Desktop.
// 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