一个练习

 Design 4 classes, God, Animal, Dog, Pig.
1. only one God.
2. Only God can create animal.
3. Animal can run.
4. Dog can bark.
5. Pig can eat.
6. God also can create plant, etc.

//TheWord.h
#ifndef THEWORLD_H
#define THEWORLD_H

#include 
  
//only one God, so use singleton mode
template<class T>
  
class SingleTon{
private:
  static T *m_Instance;
protected:
  SingleTon(){}
  ~SingleTon(){}
public:
  static T* getInstance();
};

template <class T>
  
T *SingleTon<T>
  ::m_Instance;

template <class T>
  
T* SingleTon<T>
  ::getInstance(){
  if(!m_Instance){
    m_Instance = new T();
  }
  return m_Instance;
}

// abstract class : animal
class God;
class Animal{
public:
  Animal(){}
  virtual ~Animal(){}
  virtual void run() = 0;
};

// concrete animal
class Dog : public Animal{
  friend class God;
public:
  ~Dog(){cout << "kill dog" << endl;}
  virtual void run(){cout << "dog is running" << endl;}
  void Bark(){cout << "dog is barking" << endl;}
private:
  Dog(){cout << "create dog" << endl;}
};

class Pig : public Animal{
  friend class God;
public:
  ~Pig(){cout << "Pig is killed" << endl;}
  virtual void run(){cout << "Pig is running" << endl;}
  void Eat(){cout << "Pig is eating" << endl;}
private:
  Pig(){cout << "Pig is create" << endl;}
};

// implement of God
class God{
public:
  God(){cout << "create God" << endl;}
  ~God(){cout << "kill God" << endl;}
  Dog *CreateDog(){return new Dog;}
  Pig *CreatePig(){return new Pig;}
};
#endif

你可能感兴趣的:(一个练习)