Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- using namespace std;
- class Singleton {
- static Singleton s;
- int i;
- Singleton(int x):i(x) { cout<<"Singleton ready!!!\n"; }
- Singleton(const Singleton&);
- Singleton& operator=(Singleton&);
- public:
- static Singleton& instance() {
- cout <<"Singleton used:\n";
- return s;
- }
- int getValue() { return i; }
- void setValue(int x) { i=x; }
- };
- Singleton Singleton::s(7777);
- class SingletonM {
- int i;
- SingletonM(int x):i(x) { cout<<"Mayers Singleton ready!!!\n"; }
- SingletonM(const SingletonM&);
- SingletonM& operator=(SingletonM&);
- public:
- static SingletonM& instace() {
- static SingletonM s(5555);
- return s;
- }
- int getValue() { return i; }
- void setValue(int x) { i=x; }
- ostream& ins(ostream& os) const {
- return os<<i;
- }
- };
- ostream& operator<<(ostream& os, SingletonM& obj) {
- return obj.ins( os );
- }
- template <class T> class SingT {
- private:
- SingT(const SingT&);
- SingT& operator=(SingT&);
- public:
- static T& instance() {
- static T t;
- return t;
- }
- protected:
- SingT() {}
- virtual ~SingT() {}
- };
- class SClass: public SingT<SClass> {
- protected:
- friend class SingT<SClass>;
- SClass() {cout <<"Singletonized instance ready!!!\n";}
- public:
- double fun1(double x) { return x*x; }
- double fun2(double x) { return sqrt(x); }
- };
- class Dependant {
- public:
- Dependant() {cout <<"Dependant instance ready!!!\n";}
- double x2(double x) {
- return SClass::instance().fun1(x);
- }
- double sqrt(double x) {
- return SClass::instance().fun2(x);
- }
- };
- int main() {
- {
- Singleton& s = Singleton::instance();
- cout << s.getValue() << endl;
- Singleton& s2 = Singleton::instance();
- s2.setValue(9999);
- cout << s2.getValue() << endl;
- }
- {
- SingletonM& s = SingletonM::instace();
- cout << s << endl;
- SingletonM& s2 = SingletonM::instace();
- s2.setValue(9999);
- cout << s2 << endl;
- }
- {
- Dependant d;
- double r = d.x2(5);
- cout <<"5 * 5 = "<< r << endl;
- double q = d.sqrt(r);
- cout <<"sqrt(25) = "<< q << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment