设计模式,是一种指导思想,是一种需要融合进代码设计的一种提纲挈领。
今天进入工厂模式探究:
简单工厂:
简单工厂即在工厂类中,根据所输入产品的类型,生产对应的产品。但是,这样的话,工程类就需要包含所有产品的生产实现。例子如下:
#include <iostream> using namespace std; enum CAR_TYPE { ROLLSROYCE, BENTLEY, MAYBACH, LAMBORGHINI, FERRARI, ASTONMARTIN }; class Car { public: Car(){} ~Car(){} virtual void showType(){} /* data */ }; class RollsRoyce : public Car { public: RollsRoyce(){} ~RollsRoyce(){} void showType() { cout << "Tish is RollsRoyce, from German." << endl; } /* data */ }; class Bentley : public Car { public: Bentley(){} ~Bentley(){} void showType() { cout << "This is Bentley, from England." << endl; } /* data */ }; class Maybach : public Car { public: Maybach(){} ~Maybach(){} /* data */ void showType() { cout << "This is Maybach, from Netherland." << endl; } }; class CarFactory { public: CarFactory(){} ~CarFactory(){} static Car* CreateFactory( enum CAR_TYPE carType ) { if ( ROLLSROYCE == carType ) { /* code */ return new RollsRoyce(); } else if ( BENTLEY == carType ) { return new Bentley(); } else if ( MAYBACH == carType ) { return new Maybach(); } else { return NULL; } } /* data */ }; void TestSimpleFactory() { // CarFactory carfactory; Car* pCar = CarFactory::CreateFactory( ROLLSROYCE ); pCar->showType(); delete pCar; pCar = CarFactory::CreateFactory( BENTLEY ); pCar->showType(); delete pCar; } int main() { TestSimpleFactory(); return 0; }
上例中工厂类方法中,因为不涉及到其他的成员属性,所以使用static 类静态方法。
class Car(object): """docstring for Car""" def __init__(self): self.speed = None class Rollsroyce( Car ): """docstring for """ def __init__(self ): self.name = "Rollsroyce" def showType( self ): print "This is " + self.name class Bentley( Car ): def __init__( self ): self.name = "Bentley" def showType( self ): print "This is " + self.name class CarFactory(object): """docstring for CarFactory""" @classmethod def CreateCar( cls, type ): if "BENTLEY" == type: return Bentley() elif "ROLLSROYCE" == type: return Rollsroyce() if __name__ == '__main__': car = CarFactory.CreateCar( "BENTLEY" ) car.showType() car = CarFactory.CreateCar( "ROLLSROYCE" ) car.showType()