一个练习

 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值