I am working on an api, which during runtime decides which higher-level api to use, I have many abstract classes, and derived classes for each high-level api, and a context class which provides me with the correct derived classes for the job, using a function (for example):
Mesh* genMesh(data d) { if(m_useA_API) return new A_mesh(d); else return B_mesh(d); }
something like that, now the question is, is it possible to make the code less ugly ? and instead of using methods inside the context class, can I override new operator in the base class to return the appropriate derived class instance?
if not, what are some possible solutions?
tl;dr this is what i'd like to do
Mesh* m = new Mesh(data); // and the base class decides which derived class to use instead of the Context class.
Thanks.
You can not use new as factory, but you could use Implementation Pattern for it:
class Mesh {
std::unique_ptr<MeshImpl> _impl;
public:
Mesh(int data)
: _impl(
m_use_A_API
? new A_mesh(data)
: new B_mesh(data)
) {
}
MeshImpl& get_value() { return *_impl; }
};
Classes A_mesh, B_mesh are different classes that inherited from class MeshImpl and will be initialized by correct way;
Or you can improve your factory code by next way:
move your method genMesh(int) inside class Mesh
make constructors of Mesh private, for be sure that nobody call it directly.
I am a relatively new C++ programmer.
In writing some code I've created something similar in concept to the code below. When a friend pointed out this is in fact a factory pattern I read about the pattern and saw it is in similar.
In all of the examples I've found the factory pattern is always implemented using a separate class such as class BaseFactory{...}; and not as I've implemented it using a static create() member function.
My questions are:
(1) Is this in fact a factory pattern?
(2) The code seems to work. Is there something incorrect in the way I've implemented it?
(3) If my implementation is correct, what are the pros/cons of implementing the static create() function as opposed to the separate BaseFactory class.
Thanks!
class Base {
...
virtual ~Base() {}
static Base* create(bool type);
}
class Derived0 : public Base {
...
};
class Derived1 : public Base {
...
};
Base* Base::create(bool type) {
if(type == 0) {
return new Derived0();
}
else {
return new Derived1();
}
}
void foo(bool type) {
Base* pBase = Base::create(type);
pBase->doSomething();
}
This is not a typical way to implement the factory pattern, the main reason being that the factory class isn't typically a base of the classes it creates. A common guideline for when to use inheritance is "Make sure public inheritance models "is-a"". In your case this means that objects of type Derived0 or Derived1 should also be of type Base, and the derived classes should represent a more specialised concept than the Base.
However, the factory pattern pretty much always involves inheritance as the factory will return a pointer to a base type (yous does this too). This means the client code doesn't need to know what type of object the factory created, only that it matches the base class's interface.
With regard to having a static create functions, it depends on the situation. One advantage, as your example shows, is that you won't need to create an instance of the factory in order to use it.
Your factory is ok, except for the fact that you merged the factory and the interface, breaking the SRP principle.
Instead of making the create static method in the base class, create it in another (factory) class.
I read an example in the book of 'design pattern':
Maze* MazeGame::CreateMaze(MazeFactory& factory)
{
//something to do
}
class BombedMazeFactory :public MazeFactory
{
//something to defined
}
int main()
{
MazeGame game;
BombedMazeFactory factory;
game.CreateMaze(factory);
}
So, the subclass object will be send to CreateMaze() that uses the baseclass as parameter. What should I be careful, when I doing this kind of operations?
I am also not clear why sometimes the subclass functions are still virtual (they are virtual functions in base class), are there some advantages for this?
Thanks for your great help!
You should do this in order to be able to reuse the same code for many different classes. In this case you can use in the CreateMaze() function many different factories.
The keyword virtual is optional in the inheriting class. If it is there or if it is not there, the method will be virtual because you're overriding the base class's method. Personally I prefer to use it in the inheriting class too to show it is virtual and not a regular method.
I've just learned about polymorphism in my OOP Class and I'm having a hard time understanding how abstract base classes are useful.
What is the purpose of an abstract class? What does defining an abstract base class provide that isn't provided by creating each necessary function in each actual class?
The purpose of an abstract class is to define a common protocol for a set of concrete subclasses. This is useful when defining objects that share code, abstract ideas, etc.
Abstract classes have no instances. An abstract class must have at least one deferred method (or function). To accomplish this in C++, a pure virtual member function is declared but not defined in the abstract class:
class MyClass {
virtual void pureVirtualFunction() = 0;
}
Attempts to instantiate an abstract class will always result in a compiler error.
"What does defining an abstract base class provide that isn't provided
by creating each necessary function in each actual class?"
The main idea here is code reuse and proper partitioning across classes. It makes more sense to define a function once in a parent class rather than defining over and over again in multiple subclasses:
class A {
void func1();
virtual void func2() = 0;
}
class B : public A {
// inherits A's func1()
virtual void func2(); // Function defined in implementation file
}
class C : public A {
// inherits A's func1()
virtual void func2(); // Function defined in implementation file
}
Having an abstract class like "Dog" with a virtual method like "bark" allows all classes that inherit from Dog to have their bark code called in the same way, even though the Beagle's bark is implemented way differently than the Collie's.
Without a common abstract parent (or at least a common parent with a bark virtual method) it'd be difficult to do the following:
Have a Vector of type Dog that contains Collies, Beagles, German Shepherds etc and make each of them bark. With a Vector of Dogs that contains Collies, Beagles, German Shepherds all you would have to do to make them all bark is to iterate through in a for loop and call bark on each one. Otherwise you'd have to have a separate Vector of Collies, Vector of Beagles etc.
If the question is "why make Dog abstract when it could be concrete, have a virtual bark defined with a default implementation that can be overriden?", the answer would be that this may be acceptable sometimes -- but, from a design perspective, there really isn't any such thing as a Dog that isn't a Collie or a Beagle or some other breed or mix so although they are all Dogs, there is not one of them in reality that is a Dog but not some other derived class too. Also, since dogs barking is so varied from one breed to another, there is unlikely to be any real acceptable default implementation of bark that would be acceptable for any decent group of Dogs.
I hope this helps you understand the purpose: yes, you're going to have to implement bark in each subclass anyway, but the common abstract ancestor lets you treat any subclass as a member of a base class and invoke behaviors that may be conceptually similar like bark but in fact have very different implementations.
Abstract classes allow for compile time protocol enforcement. These protocols define what it means to be a part of a class family.
Another way to think of it is that a abstract class is a contract that your implementing classes must fulfill. If they do not fulfill this contract they cannot be part of the class family and they must be modified to conform to the contract. The provided contract may provide default functionality, but it also leaves it up to the sub-class to define more specific or different functionality while still remaining within the scope of the contract.
For small projects this may not seem useful but for large projects it provides conformity and structure as it provides documentation through the abstract class contract. This makes for more maintainable code and makes for the sub-classes to each have the same protocol making using and developing new sub-classes easier.
The purpose of an abstract class is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. (because vtable entry is not filled with memory location for virtual function we mentioned in Abstract Class)
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Example:
class mobileinternet
{
public:
virtual enableinternet()=0;//defines as virtual so that each class can overwrite
};
class 2gplan : public mobileinternet
{
private:
int providelowspeedinternet(); //logic to give less speed.
public:
void enableinternet(int) {
// implement logic
}
};
//similarly
class 3gplan : public enableinternet
{
private: high speed logic (different then both of the above)
public:
/* */
}
here in this example, you can understand.
I have a dog. Abstract class dog with a method bark. My particular dog makes one bark. Other dogs bark in a different way. So defining a dog in the abstract way is useful.
Abstract classes are used to define an interface to be implemented. See some references:
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes
An abstract class AbstractClass as a base class is needed when there is functionality that is desired for all objects that have a type deriving from AbstractClass, but cannot sensibly be implemented on the AbstractClass itself.
The old and somewhat artificial OO example of having a base class Vehicle with derived classes Car, Motorcycle, ... provides a good example here, say you want a method move() - you can implement the way that a Car or a Motorcycle moves, but Vehicles don't move in a generic way, so Vehicle::move() will have to be pure virtual and Vehicle therefore abstract.
why don't we create each necessary function in each class ? (C++)
You have to create each necessary function marked as abstract in each derived class.
If you question is, why to create abstract function in abstract class?
It allows strict run time polymorphism.
Also read Interface vs Abstract Class (general OO)
abstract class dog
{
bark();
}
// function inside another module
dogbarking(dog obj)
{
dog.bark(); // function will call depend up on address inside the obj
}
// our class
ourclass: inherit dog
{
bark()
{
//body
}
}
main()
{
ourclass obj;
dogbarking(obj);
}
we can see that dogbarking is a function written in another module. it knows only the abstract class dog. even though it can call the function bark inside ourclass. in main function we create object of ourclass and pass to function dogbarking where it received using reference object of abstract class dog.
Imagine you have two methods for displaying a string:
DisplayDialog(string s);
PrintToConsole(string s);
And you want to write some code that can be switched between these two methods:
void foo(bool useDialogs) {
if (useDialogs) {
DisplayDialog("Hello, World!");
} else {
PrintToConsole("Hello, World!");
}
if (useDialogs) {
DisplayDialog("The result of 2 * 3 is ");
} else {
PrintToConsole("The result of 2 * 3 is ");
}
int i = 2 * 3;
string s = to_string(i);
if (useDialogs) {
DisplayDialog(s);
} else {
PrintToConsole(s);
}
}
This code is tightly coupled to the specific methods used for displaying the string. Adding an additional method, changing how the method is selected, etc. will affect every piece of code that uses this. This code is tightly coupled to the set of methods we use to display strings.
Abstract base classes are a way of decoupling code that uses some functionality from the code that implements that functionality. It does this by defining a common interface to all the various ways of doing the task.
class AbstractStringDisplayer {
public:
virtual display(string s) = 0;
virtual ~AbstractStringDisplayer();
};
void foo(AbstractStringDisplayer *asd) {
asd->display("Hello, World!");
asd->display("The result of 2 * 3 is ");
int i = 2 * 3;
string s = to_string(i);
asd->display(s);
}
int main() {
AbstractStringDisplayer *asd = getStringDisplayerBasedOnUserPreferencesOrWhatever();
foo(asd);
}
Using the interface defined by AbstractStringDisplayer we can create and use as many new ways of displaying strings as we want, and code that uses the abstract interface won't need to be changed.
i want to write a library for linear program solving. Thereby several solvers such as cplex or gurobi are used. What i already have is an interface for each of them (all containing the same functions wrapping them to solver specific code).
Now I want to have a class 'LinearProgram' which can be instantiated e.g. by LinearProgram("cplex") which then invokes the cplex solver.
My first idea was to use a super class 'solver' which is a base class of all solver interfaces containing the respective functions as virtual declarations. But then I get an abstract class which can not be instantiated.
So in LinearProgram i wanted to have a variable Solver which is instantiated depending on the string given in the constructor.
I'm sure a proper solution is quite obvious, but all I can think about in the moment is not satisfying.
Thanks for your help.
This illustrates what you describe:
class Solver {
...abstract base
};
class SolverFactory {
public:
Solver* NewSolverWithName(const std::string& pSolverName);
};
class LinearProgram {
public:
LinearProgram(const std::string& pSolverName) :
d_solver(SolverFactory::NewSolverWithName(pSolverName)) {
}
private:
some_auto_pointer<Solver> d_solver;
};
class cplex_Solver : public Solver {
...
static std::string Name();
};
Solver* SolverFactory::NewSolverWithName(const std::string& pSolverName) {
if (pSolverName == cplex_Solver::Name()) {
return new cplex_Solver();
}
...
}
This is a job for two different design patterns combined.
The first is the Envelope Letter pattern, and the second is the Strategy Pattern.
Keep on with the base class that you currently have and make a derived class that simply forwards the call to an embedded pointer to the base class. The derived class is now something you can freely pass around by value.
The base class could also contain a static member function that returns a pointer to the base class. This static member function would allow you to instantiate a derived class by using a string name to look it up. That provides a convenient way to select an algorithm at runtime.
But people who knew which derived class (which strategy) they wanted could just create one with 'new' and stuff it inside an instance of the envelope class.
You can optionally do away with the envelope class if you decide to just use a shared_ptr to the base class instead.