Factory is a design pattern in common usage. Implement a toyfactory which can generate proper toy based on the given type.
Example
Toyfactory tf = Toyfactory ();
Toy Toy = Tf.gettoy (' Dog ');
Toy.talk ();
>> Wow
Toy = Tf.gettoy (' Cat ');
Toy.talk ();
>> Meow
The problem is still to examine the factory pattern factory pattern, with the previous shape Factory no difference, the difficulty is not very large, see the code is as follows:
/** * Your object would be instantiated and called as such: * toyfactory* tf = new Toyfactory (); * toy* Toy = Tf->gett Oy (type); * Toy->talk (); */classToy { Public: Virtual voidTalk ()Const=0;};classDog: PublicToy {voidTalk ()Const{cout<<"Wow"<<Endl; }};classCat: PublicToy {voidTalk ()Const{cout<<"Meow"<<Endl; }};classToyfactory { Public: /** * @param Type a String * @return Get object of the type*/Toy* Gettoy (string&type) { if(Type = ="Dog") { return NewDog (); } Else if(Type = ="Cat") { return NewCat; } returnNULL; }};
Similar topics:
Shape Factory
[Lintcode] Toy Factory Toy Factory