C++软件实现架构----工厂方法模式

工厂模式目的是在父类中创建对象的方法,在子类中实现具体实例对象

例如我们要实现不同品种的猫咪,对于父类猫来说:

class Cat{

typedef enum Color{

   RED,
   BLUE,
   BLACK,
   YELLOW

};

private:

Color m_hair_color;

Color m_eye_color;

int m_shape;

int m_hair_lenght;

public:

explicit Cat(Color hair, Color eye, int shape, int hair_length);

virtual ~Cat();

virtual const void Run(int speed) const = 0;

virtual const void Grab(int power) const = 0;

virtual const void Sleep(int time) const = 0;

virtual const int Eat(String food) const = 0;

virtual const bool Excrete(String place) const = 0;

}

我设计了作为一只猫咪应有的特征,包括区分猫咪品种的毛发眼睛颜色以及毛发长度体型等

而对于猫咪的public函数,运动吃睡即是如此

如果我们要将该类扩展为子类布偶猫时,大致代码如下:

class Ragdoll : public Cat{

private:

  int m_healthy_percent;

public:

explicit Ragdoll (Color hair, Color eye, int shape, int hair_length, int healthy_p) : Cat(hair, eye, 
 shape, hair_length){

   m_hair_color = hair;
   m_eye_color = eye;
   m_shape = shape;
   m_hair_length = hair_length;
   m_healthy_percent = healthy_p;

}

~Ragdoll (){
   
   m_hair_color = null;
   m_eye_color = null;
   m_shape = null;
   m_hair_length = null;
   m_healthy_percent = null;

}


const void Run(int speed) const override final{
   //run;
}

const void Grab(int power) override final{
   //grab;
}

const void Sleep(int time) override final{
   //sleep as long as time
}

int Eat(String food) override final{
   //eat food;
   int p_full = food/stomach;
   return p_full;
}

bool Excrete(String place) override final;
   //excete in place
   return if(excete);
}

bool IsHealthy(){
   if(m_healthy_percent){
       return true;
   }else return false;
}

这两段代码最大的区别就是布偶猫在普通猫咪的基础上多调用了一个名为m_healthy_percent的成员变量,私以为布偶容易生病,远不及其他猫咪尤其田园猫的身体健康,对于其他的父类函数均在子类中实现(一定要实现,就算没用也要实现,其次如果不加override final就意味着对于cat的子类的子类来说还需要继承这个函数),而布偶猫只是自己多了一个外部调用的判断是否生病的接口

工厂方法核心思想:耦合性相当强的代码可以抓住其大多数共同特点来创建基类和基类的虚函数接口

          然后在子类中具体实现这些接口

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值