Parameterized Factory & product classes that cannot be instantiated without the Factory - c++

I'm working on implementing a Factory class along the lines of what is proposed in this response to a previous question:
Factory method implementation - C++
It's a Factory that stores a map from strings to object creation functions so I can request different types of objects from the factory by a string identifier. All the classes this factory produces will inherit from an abstract class (Connection) providing a common interface for connections over different protocols (HTTPConnection, FTPConnection, etc...)
I have a good grasp of how the method linked to above works and have got that working.
Where I'm having problems is trying to figure out a mechanism to prevent instantiation of the Connection objects without using the Factory. In order for the Factory to do it's work, I need to provide it an object creation function to store in it's map. I can't provide it the constructor because you can't make function pointers to constructors. So, as in the link above, there has to be a seperate object creation function to return new objects. But to do this, I need to make this creation function either a static method of the class, which the client code would be able to access, or a seperate function which would require either a)that the constructor of the Connection classes be public, or b) make the constructor private and make a non class member creation function be a friend, which isn't inherited and can't be enforced by the abstract base class.
Similarly, if I just made the Factory class friends with the Connection classes it was supposed to produce so it could access their private constructors, that would work, but I couldn't enforce through the abstact base class because friends aren't inherited. Each subclass would have to explicitly be friends with the Factory.
Can anyone suggest a method of implementing what I've described above?
To reiterate the requirements:
1 - Factory that produces a variety of objects all derived from the same base class based on passed in identifier to the Factory's Create method.
2 - All the subclasses that the factory will need to produce will automatically register a creation function and identifier with the factory (see linked SO answer above)
3 - All the subclasses that the factory will produce should not be instantiable (instantiatable?) without going through the Factory
4 - Enforce #3 explicitly as part of the abstract base class using inheritance. Remove the possibility for someone to subclass from the abstract base class while also providing mechanisms to freely instantiate objects.
The overall goal of what I'm trying to achieve is to allow new Connection types to be added to the hierarchy without having to change the Factory class in any way, while also forcing all the subclasses of Connection to not be instantiable directly by client code.
I'm open to the possibility that this is not the best way to achieve what I want, and suggestions of other alternatives are welcome.
EDIT - Will add some code snippets to this when I get home to hopefully make this clearer.

If I understand you correctly I think you can put some of what you want in the METADECL macro I mention in my answer you link to, ie define a static creator function that is a friend or declare it as a static method. This will make it possible for you to restrict the constructor from public use etc.
Below I try to point out where the METADECL (and METAIMPL) should be. I leave it for you to implement what you need there (I believe in you)
Header file
class MySubClass : public FactoryObjectsRoot {
METADECL(MySubClass) // Declare necessary factory construct
:
:
};
Source file
METAIMPL(MySubClass) // Implement and bootstrap factory construct

Related

c++ base class object to call unknown methods in subclasses

I am facing this problem:
An upstream application defines a class (e.g. box), and a member (say property) with a base class type. I would make a derived class for that member, add new members and methods without updating their application.
Essentially I do box->property = make_shared<myProperty>(). Is there a way to keep the interface of calling the members and methods the same? That is, to access a property using box->property->length or box->property->GetWeight(), rather than dynamic_pointer_cast<myProperty>(box->property)->GetWeight(). The challenge here is they won't update the base property class, and I am not supposed to change box. But we wish to keep the interface the same so our customers won't complain.
Is it possible? If not, how could we do to best keep the main app and my plugin relatively independent while minimize the changes on the customer side? Any suggestions are welcome.
Looks to me like the derived class for that member property violates Liskov's substitution principle.
You mentioned not being able to modify the Box class.
But are you allowed to modify the property base class? I suggest you add your "additional" methods of your derived class to the property base class.
The intent here being that the interface between the base and derived class should be one and the same. So do this only if it makes sense design wise.

C++ How to add new functionality that shares mostly the same code?

I currently have a class that processes files on a local file system.
Class FileProcessor
{
public:
UpdateFiles();
private:
processFiles();
checkFileIsCorrupted();
}
Now, I want to add a new functionality, where the same file processing is done on files that first needed to be downloaded, but then it would call processFiles() and checkFileIsCorrupted() as before and do the same processing.
I'm wondering what's the best way to do this is.
I could change the interface for UpdateFiles() and add a parameter do determine whether I need to download the files, but modifying the public interface is clearly not ideal.
I could add a new public interface function UpdateFilesFromRemote() and thus share the private members, though this would seem to violate the single responsibility principle, which would call for the "new" functionality to be its own class.
Make a new class. This would either duplicate all the code in processFiles() and processData(), or require a new base class where processFiles() and checkFileIsCorrupted() are protected members,and all the private member they call on would also need to be moved to protected in this base class as well. However, from what I've read so far, most people seem to consider using protected to be something to avoid.
Make a new class and make processFiles() and checkFileIsCorrupted() friends of both classes. I'm assuming this would require both functions to take FileProcessor and the new class as objects (or a base class interface), so that the private members can be accessed. Although both FileProcessor and the new class would share many private members, and so that would still require them to be protected in the base class interface. Also, having a design where checkFileIsCorrupted() needs to take a FileProcessor object as input just... doesn't feel right. After all, its not actually modifying the FileProcessor object, its just a helper function to check if a file is corrupted.
Make a new class and make processFiles() and checkFileIsCorrupted() non member, non friend functions. This would mean that internal file information that is private to both classes would need to be passed as function parameters to these non-member, non friend functions, breaking encapsulation.
Either way, no solutions seems to be "good". Is there any better way to design this?
Thanks.

C++ design issue. New to templates

I'm fairly new to c++ templates.
I have a class whose constructor takes two arguments. It's a class that keeps a list of data -- it's actually a list of moves in a chess program.
I need to keep my original class as it's used in other places, but I now need to pass extra arguments to the class, and in doing so have a few extra private data members and specialize only one of the private methods -- everything else will stay the same. I don't think a derived class helps me here, as they aren't going to be similar objects, and also the private methods are called by the constructor and it will call the virtual method of the base class -- not the derived method.
So I guess templates are going to be my answer. Just looking for any hints about how might proceed.
Thanks in advance
Your guess is wrong. Templates are no more the answer for your problem than inheritance is.
As jtbandes said in comment below your question, use composition.
Create another class that contains an instance of your existing class as a member. Forward or delegate operations to that contained object as needed (i.e. a member function in your new class calls member functions of the contained object). Add other members as needed, and operations to work with them.
Write your new code to interact with the new class. When your new code needs to interact with your old code, pass the contained object (or a reference or a pointer to it) as needed.
You might choose to implement the container as a template, but that is an implementation choice, and depends on how you wish to reuse your container.
Templates are used when you want to pass at compile time parameter like values,typenames, or classes. Templates are used when you want to use exactly the same class with the same methods, but applying it to different parameters. The case you described is not this I think.
If they aren't goign to be similar objects you may want to create a specialized class (or collections of function) to use from the various other classes.
Moreover you can think of creating a base class and extending it as needed. Using a virtual private method should allow you to select the method implementation of the object at runtime instead of the method of the base class.
We may help you more if you specify what does they need to share, what does your classes have in common?
The bare bones of my present code looks like this:
class move_list{
public:
move_list(const position& pos, unsigned char ply):pos_(pos),ply_(ply){
//Calculates moves and calls add_moves(ply,target_bitboard,flags) for each move
}
//Some access functions etc...
private:
//private variables
void add_moves(char,Bitboard,movflags);
};
Add_moves places the moves on a vector in no particular order as they are generated. My new class however, is exactly the same except it requires extra data:
move_list(const position& pos, unsigned char ply,trans_table& TT,killers& kill,history& hist):pos_(pos),ply_(ply),TT_(TT),kill_(kill),hist_(hist) {
and the function add_moves needs to be changed to use the extra data to place the moves in order as it receives them. Everything else is the same. I guess I could just write an extra method to sort the list after they have all been generated, but from previous experience, sorting the list as it receives it has been quicker.

Class design to avoid need for list of base classes

I'm currently in the design phase of a class library and stumbled up on a question similar to "Managing diverse classes with a central manager without RTTI" or "pattern to avoid dynamic_cast".
Imagine there is a class hierarchy with a base class Base and two classes DerivedA and DerivedB that are subclasses of Base. Somewhere in my library there will be a class that needs to hold lists of objects of both types DerivedA and DerivedB. Further suppose that this class will need to perform actions on both types depending on the type. Obviously I will use virtual functions here to implement this behavior. But what if I will need the managing class to give me all objects of type DerivedA?
Is this an indicator of a bad class design because I have the need to perform actions only on a subset of the class hierarchy?
Or does it just mean that my managing class should not use a list of Base but two lists - one for DerivedA and one for DerivedB? So in case I need to perform an action on both types I would have to iterate over two lists. In my case the probability that there will be a need to add new subclasses to the hierarchy is quite low and the current number is around 3 or 4 subclasses.
But what if I will need the managing class to give me all objects of
type DerivedA?
Is this an indicator of a bad class design because I have the need to
perform actions only on a subset of the class hierarchy?
More likely yes than no. If you often need to do this, then it makes sense to question whether the hierarchy makes sense. In that case, you should separate this into two unrelated lists.
Another possible approach is to also handle it through virtual methods, where e.g. DeriveB will have a no-op implementation for methods which don't affect that. It is hard to tell without knowing more information.
It certainly is a sign of bad design if you store (pointers to) objects together that have to be handled differently.
You could however just implement this differing behaviour as an empty function in the base class or use the visitor pattern.
You can do it in several ways.
Try to dynamic_cast to specific class (this is a bruteforce solution, but I'd use it only for interfaces, using it for classes is a kind of code smell. It'll work though.)
Do something like:
class BaseRequest {};
class DerivedASupportedRequest : public BaseRequest {};
Then modify your classes to support the method:
// (...)
void ProcessRequest(const BaseRequest & request);
Create a virtual method bool TryDoSth() in a base class; DerivedB will always return false, while DerivedA will implement the required functionality.
Alternative to above: Create method Supports(Action action), where Action is an enum defining possible actions or groups of actions; in such case calling DoSth() on class, which does not support given feature should result in thrown exception.
Base class may have a method ActionXController * GetControllerForX(); DerivedA will return the actual controller, DerivedB will return nullptr.
Similarly, base class can provide method: BaseController * GetController(Action a)
You asked, if it is a bad design. I believe, that it depends on how much functionality is common and how much is different. If you have 100 common methods and only one different, it would be weird to hold these data in separate lists. However, if count of different methods is noticeable, consider changing design of your application. This may be a general rule, but there are also exceptions. It's hard to tell without knowing the context.

Factory Pattern in C++ -- doing this correctly?

I am relatively new to "design patterns" as they are referred to in a formal sense. I've not been a professional for very long, so I'm pretty new to this.
We've got a pure virtual interface base class. This interface class is obviously to provide the definition of what functionality its derived children are supposed to do. The current use and situation in the software dictates what type of derived child we want to use, so I recommended creating a wrapper that will communicate which type of derived child we want and return a Base pointer that points to a new derived object. This wrapper, to my understanding, is a factory.
Well, a colleague of mine created a static function in the Base class to act as the factory. This causes me trouble for two reasons. First, it seems to break the interface nature of the Base class. It feels wrong to me that the interface would itself need to have knowledge of the children derived from it.
Secondly, it causes more problems when I try to re-use the Base class across two different Qt projects. One project is where I am implementing the first (and probably only real implementation for this one class... though i want to use the same method for two other features that will have several different derived classes) derived class and the second is the actual application where my code will eventually be used. My colleague has created a derived class to act as a tester for the real application while I code my part. This means that I've got to add his headers and cpp files to my project, and that just seems wrong since I'm not even using his code for the project while I implement my part (but he will use mine when it is finished).
Am I correct in thinking that the factory really needs to be a wrapper around the Base class rather than the Base acting as the factory?
You do NOT want to use your interface class as the factory class. For one, if it is a true interface class, there is no implementation. Second, if the interface class does have some implementation defined (in addition to the pure virtual functions), making a static factory method now forces the base class to be recompiled every time you add a child class implementation.
The best way to implement the factory pattern is to have your interface class separate from your factory.
A very simple (and incomplete) example is below:
class MyInterface
{
public:
virtual void MyFunc() = 0;
};
class MyImplementation : public MyInterface
{
public:
virtual void MyFunc() {}
};
class MyFactory
{
public:
static MyInterface* CreateImplementation(...);
};
I'd have to agree with you. Probably one of the most important principles of object oriented programming is to have a single responsibility for the scope of a piece of code (whether it's a method, class or namespace). In your case, your base class serves the purpose of defining an interface. Adding a factory method to that class, violates that principle, opening the door to a world of shi... trouble.
Yes, a static factory method in the interface (base class) requires it to have knowledge of all possible instantiations. That way, you don't get any of the flexibility the Factory Method pattern is intended to bring.
The Factory should be an independent piece of code, used by client code to create instances. You have to decide somewhere in your program what concrete instance to create. Factory Method allows you to avoid having the same decision spread out through your client code. If later you want to change the implementation (or e.g. for testing), you have just one place to edit: this may be e.g. a simple global change, through conditional compilation (usually for tests), or even via a dependency injection configuration file.
Be careful about how client code communicates what kind of implementation it wants: that's not an uncommon way of reintroducing the dependencies factories are meant to hide.
It's not uncommon to see factory member functions in a class, but it makes my eyes bleed. Often their use have been mixed up with the functionality of the named constructor idiom. Moving the creation function(s) to a separate factory class will buy you more flexibility also to swap factories during testing.
When the interface is just for hiding the implementation details and there will be only one implementation of the Base interface ever, it could be ok to couple them. In that case, the factory function is just a new name for the constructor of the actual implementation.
However, that case is rare. Except when explicit designed having only one implementation ever, you are better off to assume that multiple implementations will exist at some point in time, if only for testing (as you discovered).
So usually it is better to split the Factory part into a separate class.