currently I am working on one design which is in initial stage and below is the some homework I have done so far, but it doesn't seems to be ok and I have been facing some issue with this. it is clear from below code that device factory has been used for device object and library object creation purpose. now the job is after getting device object from factory, connect function will be called which will make sure that connection successfully done and now any relevant parser (XML,JSON or other supported one)needs to be used for device to fetch the data . Now here both task (selection of device and library) has been done separately so now job is I need to impose selected library on selected object and for the same assignment operator has been overloaded in Device class but I am getting error "cannot convert 'Library*' to 'Device*' in assignment" while assigning library object to device object . apart from this I also need to use Library class as a abstract class which is not possible in current implementation.
#include<iostream>
#include<string.h>
using namespace std;
class Library
{
public:
virtual void lib_func();
virtual ~Library(){}
};
class JSON : public Library
{
public:
void lib_func()
{
cout<<"connect through USB"<<endl;
}
};
class JXML : public Library
{
public:
void lib_func()
{
cout<<"Connect through TCP"<<endl;
}
};
class XML : public Library
{
public:
void lib_func()
{
cout<<" connect through BT"<<endl;
}
};
class Device
{
public:
virtual void connect()=0;
const Device& operator =(const Device& obj);
virtual ~Device(){}
private:
Library * obj;
};
const Device& Device:: operator =(const Device& rhs)
{
Library *objorig=obj;
obj=new Library(*rhs.obj);
delete objorig;
return *this;
}
class D1: public Device
{
public:
void connect()
{
cout<<" connect through USB"<<endl;
}
};
class D2 : public Device
{
public:
void connect()
{
cout<<"Connect through TCP"<<endl;
}
};
class D3 : public Device
{
public:
void connect()
{
cout<<" connect through BT"<<endl;
}
};
class Devicefactory
{
public:
virtual Device* create_instance(const char* type)=0;
virtual Library* populate_library(const char* type)=0;
};
class factory : public Devicefactory
{
public:
Device* create_instance(const char* type)
{
if(!strcmp(type,"D1"))
{
return new D1();
}
else if(!strcmp(type,"D2"))
{
return new D2();
}
else if(!strcmp(type,"D3"))
{
return new D3();
}
return NULL;
}
Library* populate_library(const char* type)
{
if(!strcmp(type,"XML"))
{
return new XML();
}
else if(!strcmp(type,"JSON"))
{
return new JSON();
}
else if(!strcmp(type,"JXML"))
{
return new JXML();
}
return NULL;
}
};
int main()
{
Devicefactory *obj=new factory;
Device * object=obj->create_instance("D3");
Library *object1=obj->populate_library("JSON");
object->connect();
object=object1;
object->lib_func();
delete object;
delete obj;
return 1;
}
Aucun commentaire:
Enregistrer un commentaire