Which design pattern should I use when I have a class representing a data structure (aka C-style struct) and I wish to have only a single class to be able to access it.
I was thinking of simply declaring the class that represents a data structure as an inner class but wanted to know if there is a better way to design this.
eg:
class XXManager{
getXX();
setXXAtrtribute();
}
class XX{
String name;
String email;
String job;
}
Here I want to design a class XXManager which will handle the creation and managment of ‘XX’ objects and no one should be able to access XX other than through the XXManager.
5
To me it seems like you might want to take a look at the Proxy design pattern. With that said not everything you create has be based on design patterns. It might lead to some overengineering.
Making XX
an inner class, or a base class of XXManager
will both work. If you want to use it as a base class you could mark it abstract to prevent direct instantiation.
You could also combine the two classes–if you really must insist that they work with an XXManager
and they do not work with XX
then removing XX
might be the simplest solution.
In all cases it feels a bit strange and raises the question of “why”? Perhaps it would be best to leave the classes independent and accessible and to rely on training or understanding enforce the standard.
Cannot quickly find any links, but I was taught that naming something an XXManager is a “code smell” and you should strongly consider naming it XX.
Why do you want an Anemic class XX with a separate XXManager?
Sometimes it makes sense to have a separate manager, e.g. if you are religiously following MVC, or a Database is involved, but is that the case here?
Assuming you want to do this, an inner class is one solution. Alternatively, in Java you could put all the classes in the same package and use package access. That isn’t perfect, as an unscrupulous hacker could create a rogue class in the same package and abuse your data. So don’t do that if you are creating some security library. Bu if the code is internal and you trust your fellow coders it is a good solution.
1
I make an assumption that your implementation language is Java, due to the syntax in the description.
Your methods getXX and setXX of XXManager indicates that another class is responsible for both creating and using your XX class. Thus it cannot be a private inner class of XXManager.
STW has a point in that Manager is a bad word for a class. What does it really do? To me it seems to be holding just an instance of XX and nothing more, in which case it doesnt really make sense for the class to exist.