Lets suppose i have a super class WorkStation, and two subclass StationNormal, StationAdvanced. I have another class Robot, which has a WorkStation pointer that will start as a StationAdvanced but it can change, but my class WorkStation is a abstract class. I think class Robot should be something like this:
class Robot{
private:
WorkStation * actualStation;
...
}
My question is how Robot class constructor should be defined if my class WorkStation is abstract.
I think the following should be sufficient:
class Robot{
private:
WorkStation * actualStation;
public:
Robot();
Robot(WorkStation * w);
}
Robot::Robot() // constructor that takes no arguments
{
actualStation = new StationAdvanced();
}
Robot::Robot(WorkStation * w) // constructor that takes specific WorkStation
{
actualStation = w;
}
You can invoke it with:
Robot rob1(),
rob2(new StationAdvanced()),
rob3(new StationNormal());
You need to let StationNormal and StationAdvanced inherit WorkStation
An example would be:
class StationNormal:public WorkStation
{
....
}
public Robot(WorkStation* workStation)
{
actualStation = workStation;
}
In main method for example:
new Robot(new StationNormal()) ;
Well, in your constructor you would instantiate the actual WorkStation and tell the pointer (WorkStation * actualStation) to point to it. Put this in your constructor:
this->actualStation = new StationAdvanced(...)
Related
My goal here was, instead of placing all methods in ServerInterface(superclass), i wanted to place the methods in child classes to organize the code better.
class ServerInterface
{
public:
Router* router = new Router();
Client* client = new Client();
ServerInterface() {
} //Creates new Router and Client instance
};
class Router : public ServerInterface
{
public:
Router() {}
void randomRouterFunction() {}
};
class Client : public ServerInterface
{
public:
Client() {}
virtual void randomClientFunction() {};
};
class ProductionServer : public ServerInterface
{
public:
ProductionServer() {}
};
int main() {
ProductionServer* productionServer = new ProductionServer();
productionServer->router->randomRouterFunction(); //causes it to not debug
return 0;
}
In my situation I am only allowed to access to ProductionServer which has to inherit from ServerInterface in my code.
So instead of calling productionServer->randomRouterFunction() or productionServer->randomClientFunction(), i wanted to be able to call productionServer->Router->randomRouterFunction() etc
Even though intellisense tells me that it's all working fine, trying to run my code i recieve
main:289:20: error: 'class ProductionServer' has no member named
'router'
productionServer->router->randomRouterFunction();
Is this even feasible to accomplish? The reason for thinking it may not work is cause the superclass creates a member of Router which is the child class, and then the router child class creates another superclass since it inherits it, which then creats another router child class in the superclass.... and it would be an infinite loop? XD
ps. The randomFunction() could be any method, just used as an example.
The problem is with the design. You can compile this but when you create a ProductionServer it will instantiate a ServerInterface which will create a Router and a Client and those will both also instantiate a ServerInterface that will create a Router and a Client and so on - until you get a stack overflow.
In order to get this in some working condition, you need to add something that breaks that cycle so that it doesn't instantiate Routers and Clients endlessly.
I have a problem with saving some variables from State abstract method into the File in Memento Pattern. The error is 'Non accessible in scope'.
Here are the pieces of code:
State class.
public abstract class State
{
protected int W;
public int getW()
{
return W;
}
public void setW(int w)
{
W = w;
}
}
Memento class.
public class Memento {
private int w, h;
private double health;
private FileWriterUtil fileWriter = new FileWriterUtil("data.txt");
private FileWriterCaretaker caretaker = new FileWriterCaretaker();
public void Save() {
//here is the error in two lines under.
w = state.State.this.getW();
h = state.State.this.getH();
String strI = Integer.toString(w);
String strII = Integer.toString(h);
String str = strI+strII;
fileWriter.write(str);
caretaker.save(fileWriter);
}
}
I know it shouldn't work, but how to solve it?
You have at least three problems.
First, you need to construct an instance of the State class someplace in your Momento class, maybe as a member in the constructor? I don't know what you are trying to accomplish.
Second, State is abstract so you are going to have to define a subclass that you can instantiate. something like this:
class MyState extends State...
And instantiate MyState.
Thirdly, State doesn't declare a getH() method. How do you expect to call that?
Oh, one more thing:
state.State.this
Your use of "this" doesn't seem right.
Which approach is better: I tried to find it on web, but I couldn't get a better answer.
1.
public class OtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
OtherClass oClass = new OtherClass();
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
2.
public class TestClass
{
public int Fun1()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
public int Fun2()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
}
I think it depends on what you are trying to test.
If you're testing the effects of a sequence of functions being executed on the same class instance then you might want to create a single instance (such as stress testing)
But otherwise I'd say it's always better to create a new instance of the class in each test function to ensure that the context of each test is predictable. If your test methods shared an instance of a class, and one test method fails and corrupts the state of the object under test, your subsequent test may fail for no other reason than the state of the object under test was corrupted by the previous failed test (it might appear the multiple tests are failing when in fact only one of the early ones is a true failure).
Depends on the scenario, if the class is gonna be shared on multiple functions and there are no specific arguments needed to create an instance of that class then it's better of being at the class level.
Let's say you're using the Fun1 and Fun2 often, having the instance creation on the method will have instance creation overhead rather than it being at the class level having a single instance, or better yet, make it static or make it singleton if you're sure that it's going to be a single instance throughout the whole app.
One benefit of having it in the class level is if you're doing unit testing, you can make an interface like IOtherClass and Inject it in the constructor of TestClass.
It would look something like this.
public class OtherClass : IOtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
IOtherClass oClass;
public TestClass(IOtherClass _oClass)
{
oClass = _oClass;
}
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
You're better off having it as a field in the class rather than declaring a new one in each method. The reason for this is simple, there won't be a line of code in each method declaring the variable meaning that if your declaration statement changes you will only have to change it in one place, not every method. Also it will make your code easier to read and add to because this line won't be duplicated everywhere.
Just remember if that field needs to be disposed your class should implement the IDisposable interface.
Say i have an hierarchy of Shape objects, each has its own data (polyline has list of vertices, circle has a center and radius, etc).
I want to be able to perform operations on each shape, such as Draw, Snap to some point, split to two shapes at a specific point, etc.
One way to do it is to add a method to Shape interface for each operation. However, in that case i will have to modify my model interface every time a new operation is added. It does not sound correct to me. I thought of the following solution and would like to here your opinion or other solutions.
I will add an interface of ShapeOperationsFactory and the following method to Shape interface:
class Shape
{
public:
virtual ShapeOperationFactory* createShapeOperationsFactory() = 0;
};
class Circle : public Shape
{
public:
virtual ShapeOperationsFactory* createShapeOperationsFactor();
};
ShapeOperationsFactory* Circle::createShapeOperationsFactory()
{
return new CircleShapeOperationsFactory();
}
ShapeOperationsFactory will be able to create a set of operations classes that are specific for the shape:
class ShapeOperationsFactory
{
public:
virtual ShapeDrawer* createDrawer() = 0;
virtual ShapeSnapper* createSnapper() = 0;
virtual ShapeSplitter* createSplitter() = 0;
};
class CircleShapeOperationsFactory : public ShapeOperationsFactory
{
public:
virtual ShapeDrawer* createDrawer();
virtual ShapeSnapper* createSnapper();
virtual ShapeSplitter* createSplitter();
}
ShapeDrawer* CircleShapeOperationsFactory::createDrawer()
{
return new CircleShapeDrawer();
}
ShapeSnapper* CircleShapeOperationsFactory::createSnapper()
{
return new CircleShapeSnapper();
}
ShapeSplitter* CircleShapeOperationsFactory::createSplitter()
{
return new CircleShapeSplitter();
}
In this implementation the Shape interface will not change when new operations are added. For new shape i will need to implement a new operations factory and a class per operation. For new operations i will need to add a method to the operations factory class and a class implementing the operation for each shape.
Making your classes more modular by creating an Operator class I think is great, but this is not really a factory. Factory usually involved creating an object base on some message, for example on a unserialization process.
For your case you could have an Operator member in your base class and in the constructor of your derived class you assign that member to the appropriate Operator derived class.
A solution could be to use the visitor design pattern. The purpose of this design pattern :
the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.
The principle is simple:
You create a visitor class:
class Visitor
{
public:
virtual void visit(Circle*) = 0;
virtual void visit(Polyline*) = 0;
...
};
You add this method to Shape:
virtual void accept(class Visitor*) = 0;
Then you implements this method in each Shape sub class.
void Circle::accept(Visitor *v)
{
v->visit(this);
}
And then you have to create one visitor per operation:
class Drawer: public Visitor
{
public:
Drawer()
{
}
void visit(Circle* c)
{
drawCircle(c);
}
void visit(Polyline*p)
{
drawPolyline(p);
}
...
};
You could also delegate each visit method to a service: (visit(Circle* c) to a CircleDrawer).
void visit(Circle* c)
{
circleDrawer->draw(c);
}
void visit(Polyline*p)
{
polylineDrawer->draw(p);
}
If you want to add an operation, you will have to create a new visitor sub class.
If you want to add a shape, you will have to add a new method on each visitor.
The visitor collaborare really well with the composite design pattern (heavily use in gui programming). The visitor pattern can be used in addition with the composite pattern. The object structure can be a composite structure. In this case in the implementation of the accept method of the composite object the accept methods of the component object has to be invoked.
Note:
I am not a c++ programmer, feel free to edit and make the code syntactically correct.
consider this class:
class baseController {
/* Action handler array*/
std::unordered_map<unsigned int, baseController*> actionControllers;
protected:
/**
* Initialization. Can be optionally implemented.
*/
virtual void init() {
}
/**
* This must be implemented by subclasses in order to implement their action
* management
*/
virtual void handleAction(ACTION action, baseController *source) = 0;
/**
* Adds an action controller for an action. The actions specified in the
* action array won't be passed to handleAction. If a controller is already
* present for a certain action, it will be replaced.
*/
void attachActionController(unsigned int *actionArr, int len,
baseController *controller);
/**
*
* checks if any controller is attached to an action
*
*/
bool checkIfActionIsHandled(unsigned int action);
/**
*
* removes actions from the action-controller filter.
* returns false if the action was not in the filter.
* Controllers are not destoyed.
*/
bool removeActionFromHandler(unsigned int action);
public:
baseController();
void doAction(ACTION action, baseController *source);
};
}
and this subclass
class testController : public baseController{
testController tc;
protected:
void init(){
cout << "init of test";
}
void handleAction(ACTION action, baseController *source){
cout << "nothing\n";
}
};
The compiler comes out with an error on the subclass on the member
testController tc;
..saying
error: field ‘tc’ has incomplete type
but if I remove that and I instatiate the class it works... is there a way to avoid this error??? It looks so strange to me....
one day someone asked me why a class can't contain an instance of itself and i said;
one day someone asked me why a class can't contain an instance of itself and i said;
one day someone asked me why a class can't contain an instance of itself and i said;
...
use indirection. a (smart) pointer or refrence to a testController rather than a testController.
Your code is trying to embed an entire instance of testController inside itself, which is impossible. Instead, you want a reference:
testController &tc;
or a pointer
testController *tc;
It won't compile because you're declaring a member variable 'tc' that is an instance of itself. You're not using tc in the subclass; what is your intent here?
You can not create an object of the class inside that class itself. Probably what you intend to do is to keep a pointer to the class. In that case you should use it as testController* BTW, why do you want to do that? It looks a bit strange to me.
(A bit late to the party, but ...)
Maybe gotch4 meant to type something like this?
class testController : public baseController
{
public:
testController tc(); // <- () makes this a c'tor, not a member variable
// ( ... snip ... )
};