class M {
};
class E {
public:
~E();
private:
MyVector mv;
};
E::~E() {
mv.clear()
}
typedef MyHashMap<M*, E*> EMap;
typedef MyHashMap<M*, E*>::iterator EMapItr;
class A : public class Base {
public:
~A();
const EMap& getEMap() { return p_emap};
virtual void func();
protected:
EMap p_Map;
};
A::~A() {
EMapItr eMItr = p_Map.beginRandom();
for(; eMItr; ++eMItr) {
delete eMItr.value();
}
}
class DB {
public fill(EMap* p_Map);
};
class Derived: public A {
private:
DB dp;
};
class GUI {
public:
void guiFunc();
}
void GUI:guiFunc() {
Derived* d = new Derived;
d->func();
}
void Derived::func() {
db.fill(&p_map);
}
Please note MyHashMap is my customised hashmap . the functionality is same as std:hashmap
Please note MyVector is customise form of std::vector . the functionality is same as std:vector
I do not want to delete Pointer of M class M*
is the following code correct or do yo see any problem in the same
A::~A() {
EMapItr eMItr = p_Map.beginRandom();
for(; eMItr; ++eMItr) {
delete eMItr.value();
}
}
Also do we need to clear the vector as below or it will be automatically taken care
E::~E() {
mv.clear()
}
standard library containers don't need to be cleared in destructors because they take care of their own memory management. It is best to do the same with you custom containers because that is generally expected and anyway the best way to avoid memory issues.
Related
I am very new to c++ so I am trying to get a feeling of how to do things the right way in c++. I am having a class that uses one of two members. which one gets determined at instantiation. It looks something like
main() {
shared_pointer<A> a = make_shared<A>();
if ( checkSomething ) {
a->setB(make_shared<B>());
} else {
a->setC(make_shared<C>());
}
a->doStuff();
class A {
public:
doStuff() {
/*here I want to do something like call
m_b->doStuff() if this pointer is set and m_c->doStuff() if
that pointer is set.*/
}
setB( B* p ) { m_b = p; }
setC( C* p ) { m_c = p; }
B* m_b;
C* m_c;
}
}
B and C are some classes with doStuff() member function
There are many members like doStuff. Ideally I would avoid checking for nullptr in each of them. What is the best/most efficient/fastest way to create a switch between those two members?
Is there a way to use a static pointer so that I have a member
static **int m_switch;
and do something like
m_switch = condition ? &m_b : &m_c;
and call
*m_switch->doStuff();
Does the compiler here also replace the extra pointer hop because it is a static?
Is there any other smart way to do those switches?
Normally, class A would be an interface class, which both B and C would inherit and implement. But it sounds like you cannot do this for whatever reason.
Since you want to emulate this, you can start by making the interface:
class A_interface
{
public:
virtual void doStuff() = 0;
virtual void doThings() = 0;
virtual void doBeDoBeDo() = 0;
};
And then you make a template wrapper:
template< class T >
class A : public A_interface
{
public:
void doStuff() override { target.doStuff(); }
void doThings() override { target.doThings(); }
void doBeDoBeDo() override { target.doBeDoBeDo(); }
private:
T target;
};
This essentially does half of what your own example class A was trying to do, but now you can use a common interface. All you need to do is construct the correct templated version you want:
std::shared_ptr<A_interface> a;
if( checkSomething ) {
a = std::make_shared<A<B>>();
} else {
a = std::make_shared<A<C>>();
}
a->doStuff();
You need to have both members implement a common interface to use them similarly. But in order to do that, you need to define the interface and relay the calls to the B and C classes.
// existing classes
class B
{
public:
void doStuff() { std::cout << "B"; }
};
class C
{
public:
void doStuff() { std::cout << "C"; }
};
// define your interface
class I
{
public:
virtual void doStuff() = 0;
};
// new classes
class D : public B, public I
{
public:
void doStuff() override { B::doStuff(); }
};
class E : public C, public I
{
public:
void doStuff() override { C::doStuff(); }
};
// your A class
class A
{
public:
D* b = nullptr; // now type D
E* c = nullptr; // now type E
// your toggle
I* getActive()
{
if (b)
return b;
else
return c;
}
// simple doStuff() function
void doStuff()
{
getActive()->doStuff();
}
};
int main()
{
A a;
if (true)
a.b = new D; // need to initialize as D
else
a.c = new E; // need to initialize as E
a.doStuff(); // prints B
}
But typing this up made me realize that defining D and E could get really tiresome and against what you're trying to save. However, you can define a template to create them like #paddy has done.
There's no one-size-fits-all solution for your problem. What to use depends on your particular problem. A few possible answers:
Interfaces
Strategy Pattern
Pointers (to hold a function or class which implements doStuff)
An interface is like a contract. Any class which inherits from the interface must implement its members. For instance,
class IDoesStuff
{
public:
virtual ~IDoesStuff() {};
virtual void DoStuff() = 0;
};
Can now be used by other classes:
class Foo : public IDoesStuff
{
public:
virtual void DoStuff()
{
// ....
}
};
class Bar : public IDoesStuff
{
public:
virtual void DoStuff()
{
// ....
}
};
And now, in general, one may do:
Foo foo;
IDoesStuff *stuffDoer= &foo;
stuffDoer->doStuff();
This can be used in your particular use case as follows:
class A
{
IDoesStuff *stuffDoer; // Initialize this at some point.
public:
void doStuff() { stuffDoer->doStuff(); }
};
First you must change your memebr variables m_b and m_c to std::shared_ptr.
Add a member variable of type std::function(void()) to hold the target function you want to call. In your sample it is do_stuf.
In your setter functions you can bind target function to your std::function and in do_stuf just call std::function.
(You need a C++11 compiler)
class B
{
public:
void doStuff()
{
}
};
class C
{
public:
void doStuff()
{
}
};
class A
{
public:
void doStuff()
{
m_target_function();
}
void setB(std::shared_ptr<B> p)
{
m_b = p;
m_target_function = std::bind(&B::doStuff, m_b.get());
}
void setC(std::shared_ptr<C> p)
{
m_c = p;
m_target_function = std::bind(&C::doStuff, m_c.get());
}
std::shared_ptr<B> m_b;
std::shared_ptr<C> m_c;
std::function<void()> m_target_function;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::shared_ptr<A> a = std::make_shared<A>();
bool use_B = false;
if (use_B)
{
a->setB(std::make_shared<B>());
}
else
{
a->setC(std::make_shared<C>());
}
a->doStuff();
}
class Base
{
public:
virtual ~Base() {}
virtual void Foo() = 0;
};
class FirstDerived: public Base
{
public:
void Foo() { cout << "FirstDerived" << endl; }
};
class SecondDerived: public Base
{
public:
void Foo() { cout << "SecondDerived" << endl; }
};
union PreallocatedStorage
{
PreallocatedStorage() {}
~PreallocatedStorage() {}
FirstDerived First;
SecondDerived Second;
};
class ContainingObject
{
public:
Base* GetObject()
{
if (!m_ptr)
{
// TODO: Make runtime decision on which implementation to instantiate.
m_ptr = new(&m_storage) SecondDerived();
}
return m_ptr;
}
~ContainingObject()
{
if (m_ptr)
{
m_ptr->~Base();
}
}
private:
PreallocatedStorage m_storage;
Base* m_ptr = nullptr;
};
int main()
{
auto object = make_unique<ContainingObject>();
// ...
// Later, at a point where I don't want to make more heap allocations...
// ...
auto baseObject = object->GetObject();
baseObject->Foo();
return 0;
}
What I'm trying to achieve here:
I need to instantiate a class that has virtual methods.
At the point in time I know exactly which derived class to instantiate, I cannot make further heap allocations (this is just out of curiosity, so the exact reason why is not relevant).
Hence, I want to somehow pre-allocate enough space to hold any possible implementation, and then decide later what class I'm going to instantiate in it.
Is there anything standards-non-compliant/undefined behavior in the above code?
The code is correct. See the comments on the question for some interesting insights, particularly the use of std::aligned_union which can be used as a generic replacement for the PreallocatedStorage union above.
#include <iostream>
class EquationOfMotion
{
public:
// other attributes
virtual void findNextTimeStep() = 0;
};
class SystemModel
{
public:
EquationOfMotion* p_eom;
// other atributes
SystemModel(EquationOfMotion* new_p_eom)
{
p_eom = new_p_eom;
}
};
class VehicleEquationOfMotion: public EquationOfMotion
{
public:
VehicleEquationOfMotion(...){/* initialise attribute*/}
virtual void findNextTimeStep(){}
};
class Vehicle: public SystemModel
{
// ???? Implementation ?????
}
Vehicle is a specialization of SystemModel where p_eom points to VehicleEquationOfMotion.
I would like to initialise, an instance of VehicleEquationOfMotion and point to it p_eom in Vehicle. I want it to be defined only within the scope of Vehicle, and at the same time, not to use heap.
Is it even possible to reside VehicleEquationOfMotion object inside Vehicle without using the heap? (If not, please suggest where the design has gone wrong).
Might be helpful: I thought about the implementation in this question but ran into trouble (see the question).
If I got your question correctly, then do it like this:
class FooChild : public FooParent
{
public:
FooChild (int pX):m_BarChild(pX), FooParent(&m_BarChild) // point p_barPar to instance of BarChild (i.e. m_BarChild)
{
}
private:
BarChild m_BarChild; // instance of BarChild resided in the stack(not the heap) and is local to FooChild
}
If you want to have FooParent.p_barPar to be pointing to a BarChild that resides inside FooChild, you might need to add a default ctor to FooParent and a method as follows as well: set_p_barPar(BarChild* new_p_bar){p_barPar = new_p_bar;}. So you get:
class FooParent
{
public:
BarParent* p_barPar;
FooParent (){}
FooParent (BarChild* new_p_bar)
{
p_barPar = new_p_bar;
std::cout << p_barPar->x << std::endl;
}
protected:
set_p_barPar(BarChild* new_p_bar)
{
p_barPar = new_p_bar;
}
}
Then you can implement FooChild:
class FooChild : public FooParent
{
public:
FooChild(int new_x, BarChild* new_p_bar):_bar_child(new_x)
{
set_p_barPar(&_bar_child);
}
private: //? Depends on your plans
BarChild _bar_child();
}
Use a class template.
class EquationOfMotion { ... };
template <typename EOM>
class SystemDynamics
{
EOM EquationOfMotion;
...
};
class VehicleEquationOfMotion : public EquationOfMotion { ... };
class Vehicle : public SystemDynamics<VehicleEquationOfMotion> { ... };
May be this is what you want. But the design is not safe. You are passing the pointer to a uninitialized object.
class Vehicle: public SystemModel
{
public:
Vehicle(): SystemModel(&_vem)
{
}
VehicleEquationOfMotion _vem;
}
However, it is safer to do the following:
class SystemModel
{
public:
EquationOfMotion* p_eom;
// other atributes
SystemModel()
{
}
};
class Vehicle: public SystemModel
{
public:
Vehicle(): SystemModel(&_vem)
{
p_eom = &_vem;
}
VehicleEquationOfMotion _vem;
};
Say I have a class called Person, who owns three kinds of pets:
class Person
{
public:
accept(Pet a);
private:
Dog d; // is a Pet
Cat c; // is a Pet
Fish f; // is a Pet
}
Person::accept(Pet a)
{
// if pet is Dog, then
d = a;
// if pet is Cat, then
c = a;
// if pet is Fish, then
f = a;
};
I guess typeid can be used here. However, it still looks weird to me.
Is there some kind of polymorphism, virtual function or some OOP pattern that can be applied?
-- EDIT --
Sorry for the bad example here. Let me try another one:
// Usually a context contains three different resources:
class Context
{
public:
setResource(Resource *r);
private:
Buffer *b_; // is a Resource
Kernel *k_; // is a Resource
Sampler *s_; // is a Resource
};
Context::setResource(Resource *r) { // same logic as Person::accept() above }
Context::handlingBuffer() { if (b_) b_->init(); ... }
Context::run() {
if (b_ && k_) {
k_.setBuffer(b_);
k_.run();
}
}
...
In this case, looks like adding a Resource *r_[3] in Context will make things more complicated.
So, is it possible to pass a pointer of base class of Resource to setResource(), and it can automatically decide which resource to set?
Since you are holding Pets by value, you can forget polymorphism and just overload the accept member function:
class Person
{
public:
accept(const Dog& a) { d_ = a; }
accept(const Cat& a) { c_ = a; }
accept(const Fish& a) { f_ = a; }
private:
Dog d_; // is a Pet
Cat c_; // is a Pet
Fish f_; // is a Pet
};
A common method to letting code depend on the runtime type is double dispatch, a.k.a. the Visitor pattern:
class ResourceContext
{
public:
virtual void setResource(Buffer* r) = 0;
virtual void setResource(Kernel* r) = 0;
virtual void setResource(Sampler* r) = 0;
};
class Resource
{
public:
virtual void AddToContext(ResourceContext* cxt) = 0;
[... rest of Resource ...]
};
class Buffer : public Resource
{
public:
void AddToContext(ResourceContext* cxt) { cxt->SetResource(this); }
};
// Likewise for Kernel and Sampler.
class Context : public ResourceContext
{
public:
void setResource(Resource* r) { r->AddToContext(this); }
void setResource(Buffer *r) { b_ = r; }
void setResource(Kernel *r) { k_ = r; }
void setResource(Sampler *r) { s_ = r; }
private:
Buffer *b_; // is a Resource
Kernel *k_; // is a Resource
Sampler *s_; // is a Resource
};
For me the approach itself looks wrong. As #LihO said in his comment, polymorphism helps to treat different type objects in the same manner. So from polymorphism point of view, your design should look as:
// Usually a context contains three different resources:
class Context
{
public:
setResource(Resource *r);
private:
std::vector<Resource*> resources_;
};
The rest should be resolved by virtual functions of Resource class.
Using dynamic_cast often means your design is not perfect.
For your simple example code, I agree with juanchopanza. However, if you want to keep the structure of your class Person with pointers, you could use dynamic_cast<>, e.g.
struct Pet { /* ... */ };
struct Dog : public Pet { /* ... */ };
struct Cat : public Pet { /* ... */ };
struct Fish : public Pet { /* ... */ };
struct Spider : public Pet { /* ... */ };
class Person {
Dog*dog;
Cat*cat;
Fish*fish;
Spider*yuck;
template<typename PetType>
static bool accept_pet(Pet*pet, PetType*&my_pet)
{
PetType*p = dynamic_cast<PetType*>(pet);
if(p) {
my_pet = p;
return true;
}
return false;
}
public:
Person()
: dog(0), cat(0), fish(0), yuck(0) {}
void accept(Pet*pet)
{
if(accept_pet(pet,dog)) return;
if(accept_pet(pet,cat)) return;
if(accept_pet(pet,fish)) return;
if(accept_pet(pet,yuck)) return;
throw unknown_pet();
}
};
I should add, that dynamic_cast<> should be avoided if it can. Often (but not always) a design that makes a dynamic_cast<> necessary can be improved to avoid that. This also applies here, when simply overloading the accept() (as in juanchopanza's answer) is an alternative.
Inspired by #molbdnilo, I found a simpler way to achieve my goal:
class Resource
{
public:
virtual void AddToContext(Context* c) = 0;
};
class Buffer : public Resource
{
public:
void AddToContext(Context* c) { c->SetResource(this); }
};
// Likewise for Kernel and Sampler
class Context
{
public:
void SetResource(Resource *r) { r->AddToContext(this); }
void SetResource(Buffer *b) { b_ = b; }
void SetResource(Kernel *k) { k_ = k; }
void SetResource(Sampler *s) { s_ = s; }
...
private:
Buffer *b_;
Kernel *k_;
Sampler *s_;
};
It is not quite like Visitor pattern at this point, but it is relatively concise and works great.
Suppose I have the following classes:
class BaseObject {
public:
virtual int getSomeCommonProperty();
};
class Object1: public BaseObject {
public:
virtual int getSomeCommonProperty(); // optional
int getSomeSpecificProperty();
};
class BaseCollection {
public:
virtual void someCommonTask();
};
class Collection1: public BaseCollection {
public:
virtual void someCommonTask(); // optional
void someSpecificTask();
};
Each collection, derived from BaseCollection, deals with a specific object type (and only one type). But BaseCollection should be able to perform some tasks that are common to all objects, using only common object properties in BaseObject.
Currently, I have potentially three solutions in mind:
1) Store the objects list in BaseCollection, such as:
class BaseCollection {
vector<BaseObject*> objects;
};
The problem with this solution is that when I need to perform object-specific task in Collection1, I need a dynamic_cast<>, because I don't want to use virtual inherance for specific properties, applying to only one type of object. Considering that dynamic_cast<> could potentially get called millions of time per second, this seems an issue for a performance critical application.
2) Store the objects list in Collection1, such as:
class Collection1: public BaseCollection {
vector<Object1*> objects;
}
But then I need some way to access this object list in BaseCollection, to be able to perform some common tasks on them, ideally through an iterator. I would need to create a function that return a vector for the BaseCollection, but again, this does not seem very efficient, because the only way to do that is to create a new vector (potentially containing thousands of objects)...
3) Store the objects list in BaseCollection AND Collection1:
class BaseCollection {
public:
void someCommonTask(); // Use baseObjects
virtual void addObject() = 0;
protected:
vector<BaseObject*> baseObjects;
};
class Collection1: public BaseCollection {
vector<Object1*> objects;
public:
virtual void addObject() {
Object1* obj = new Object1;
objects.push_back(obj);
baseObjects.push_back(obj);
}
void someSpecificTask(); // Use objects, no need of dynamic_cast<>
}
Where the two lists actually contain the same objects. Is that as ugly as it sounds like?
I am looking for the right/correct/best design pattern for this type of problem and none of the 3 solutions exposed above really satisfies me...
Maybe it is possible to solve that problem with templates, but then I don't see a way to store a list of polymorphic collections like this:
vector<BaseCollection*> collections;
You can store all your objects of base and derived classes in one collection through the base class (smart) pointer. Using visitor design pattern and double dispatch mechanism you can call a function only on objects of a specific type without having to expose that function in the base class interface. For example:
#include <boost/intrusive_ptr.hpp>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
#include <stdio.h>
struct Visitor { // Visitor design patter
virtual void visit(struct BaseObject&) {}
virtual void visit(struct Object1&) {}
};
struct BaseObject {
unsigned ref_count_; // intrusive_ptr support
BaseObject() : ref_count_() {}
virtual ~BaseObject() {}
virtual void accept(Visitor& v) { v.visit(*this); } // Visitor's double dispatch
virtual void getSomeCommonProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
};
void intrusive_ptr_add_ref(BaseObject* p) { // intrusive_ptr support
++p->ref_count_;
}
void intrusive_ptr_release(BaseObject* p) { // intrusive_ptr support
if(!--p->ref_count_)
delete p;
}
struct Object1 : BaseObject {
virtual void accept(Visitor& v) { v.visit(*this); } // Visitor's double dispatch
virtual void getSomeCommonProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
void getSomeSpecificProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
};
template<class T, class Functor>
struct FunctorVisitor : Visitor {
Functor f_;
FunctorVisitor(Functor f) : f_(f) {}
void visit(T& t) { f_(t); } // apply to T objects only
template<class P> void operator()(P const& p) { p->accept(*this); }
};
template<class T, class Functor>
FunctorVisitor<T, Functor> apply_to(Functor f)
{
return FunctorVisitor<T, Functor>(f);
}
int main()
{
typedef boost::intrusive_ptr<BaseObject> BaseObjectPtr;
typedef std::vector<BaseObjectPtr> Objects;
Objects objects;
objects.push_back(BaseObjectPtr(new BaseObject));
objects.push_back(BaseObjectPtr(new Object1));
for_each(
objects.begin()
, objects.end()
, boost::bind(&BaseObject::getSomeCommonProperty, _1)
);
for_each(
objects.begin()
, objects.end()
, apply_to<BaseObject>(boost::bind(&BaseObject::getSomeCommonProperty, _1))
);
for_each(
objects.begin()
, objects.end()
, apply_to<Object1>(boost::bind(&Object1::getSomeSpecificProperty, _1))
);
}
Output:
$ ./test
virtual void BaseObject::getSomeCommonProperty()
virtual void Object1::getSomeCommonProperty()
virtual void BaseObject::getSomeCommonProperty()
void Object1::getSomeSpecificProperty()
I think you should go for option 1 but use a static cast instead. After all the derived collection knows the type of the member variable for sure.
This answer explains it very well.
Id use nested adapter as in below example. You have to specialize it for every class you want to do a fancy update
!The example has memory leak - allocated A, B, Q objects are not deleted!
#include <iostream>
#include <vector>
#include <algorithm>
class Q
{
public:
virtual void Foo()
{
std::cout << "Q::Foo()" << std::endl;
}
};
class A
{
public:
virtual void Foo()
{
std::cout << "A::Foo()" << std::endl;
}
};
class B : public A
{
public:
virtual void Foo()
{
std::cout << "B::Foo()" << std::endl;
}
virtual void BFoo()
{
std::cout << "B::BFoo()" << std::endl;
}
};
template <typename ElementType>
class C
{
public:
template <typename T>
void add(T* ptr){m_Collection.push_back(std::unique_ptr<Adapter>(new ConcreteAdapter<T>(ptr)));}
void updateAll()
{
std::for_each(m_Collection.begin(), m_Collection.end(), [&](std::unique_ptr<Adapter> &adapter)->void{adapter->update();});
}
private:
class Adapter
{
public:
virtual ElementType* get() = 0;
virtual void update(){get()->Foo();}
};
template <typename T>
class ConcreteAdapter : public Adapter
{
public:
ConcreteAdapter(T* ptr) : m_Ptr(ptr){}
virtual T* get(){return m_Ptr;}
protected:
T* m_Ptr;
};
template <>
class ConcreteAdapter<B> : public Adapter
{
public:
ConcreteAdapter(B* ptr) : m_Ptr(ptr){}
virtual B* get(){return m_Ptr;}
virtual void update()
{
get()->Foo();
get()->BFoo();
}
private:
B* m_Ptr;
};
std::vector<std::unique_ptr<Adapter>> m_Collection;
};
int main()
{
C<A> c;
c.add(new A());
c.add(new B());
//c.add(new Q()); //error - correct
c.updateAll();
return 0;
}
Maybe this will do the trick here ?
class CollectionManipulator {
public:
void someCommonTask(BaseCollection& coll) {
for(unsigned int i = 0; i < coll.size(); i++)
someCommonTask(coll.getObj(i));
}
private:
void someCommonTask(BaseObject*); // Use baseObjects
};
class BaseCollection {
friend class CollectionManipulator;
private:
virtual BaseObject* getObj(unsigned int) = 0;
virtual unsigned int size() const = 0;
};
class Collection1 : public BaseCollection {
vector<Object1*> objects;
public:
virtual void addObject() {
Object1* obj = new Object1;
objects.push_back(obj);
baseObjects.push_back(obj);
}
void someSpecificTask(); // Use objects, no need of dynamic_cast<>
private:
BaseObject* getObj(unsigned int value) {
return object[value];
}
unsigned int size() const {
return objects.size();
}
}
If you want abstract your container in Collection1 (like using list instead using vector), to use it in Manipulator, create an abstract iterator...
I think the solution should be a mix of factory method pattern and template method pattern. Take a look at those to refine your design.
Edit: Here is a sample code. GenericProduct is the BaseObject, it provides two methods, one that is general (though it could be overridden), and a specific method which does nothing, it is not a pure virtual so this class can be instantiated. SpecificProduct is a subclass, which implements the specific method in some way.
Now, Factory class is an abstract class that defines an interface for creating specific products by specific factories, it defines a pure virtual method createProduct which creates the product. Two concrete factories are created GenericFactory and SpecificFactory which create specific products.
Finally, the Consumer abstract class (which corresponds to BaseCollection in your code), it defines a pure virtual method for creating a factory createFactory in order to force subclasses to create their own concrete factories (and hence, the correct products). The class also define a method fillArray (prototype pattern) to fill the array with products created by the factory.
#include <iostream>
#include <vector>
using namespace std;
class GenericProduct{
public:
virtual void getSomeCommonProperty()
{
cout<<"Common Property\n";
}
virtual void getSomeSpecificProperty()
{
cout<<"Generic Has Nothing Specific\n";
}
};
class SpecificProduct : public GenericProduct{
public:
virtual void getSomeSpecificProperty()
{
cout<<"Specific Product Has a Specific Property\n";
}
};
class Factory
{
public:
virtual GenericProduct* createProduct() = 0;
};
class GenericFactory : public Factory
{
public:
virtual GenericProduct* createProduct()
{
return new GenericProduct();
}
};
class SpecificFactory : public Factory
{
public:
virtual GenericProduct* createProduct()
{
return new SpecificProduct();
}
};
class Consumer
{
protected:
vector<GenericProduct*> gp;
Factory* factory;
protected:
virtual void createFactory() = 0;
public:
void fillArray()
{
createFactory();
for(int i=0; i<10; i++)
{
gp.push_back(factory->createProduct());
}
}
virtual void someCommonTask()
{
cout<<"Performaing a Common Task ...\n";
for(int i=0; i<10; i++)
{
gp[i]->getSomeCommonProperty();
}
}
virtual void someSpecificTask()
{
cout<<"Performaing a Specific Task ...\n";
for(int i=0; i<10; i++)
{
gp[i]->getSomeSpecificProperty();
}
}
};
class GenericConsumer : public Consumer
{
virtual void createFactory()
{
factory = new GenericFactory();
}
};
class SpecificConsumer : public Consumer
{
virtual void createFactory()
{
factory = new SpecificFactory();
}
};
int main()
{
Consumer* c = new GenericConsumer();
c->fillArray();
c->someCommonTask();
return 0;
}