赞
踩
工厂模式目的是在父类中创建对象的方法,在子类中实现具体实例对象
例如我们要实现不同品种的猫咪,对于父类猫来说:
- 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的子类的子类来说还需要继承这个函数),而布偶猫只是自己多了一个外部调用的判断是否生病的接口
工厂方法核心思想:耦合性相当强的代码可以抓住其大多数共同特点来创建基类和基类的虚函数接口
然后在子类中具体实现这些接口
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。