Class Dependency and Hierarchy
I'm quite challenged (re开发者_运维技巧ad retarded) when it comes to understanding programming with classes. So far I've only written some very basic classes.
In VBA and VB6 I've often seen where ClassB can only become a valid object through a method of ClassA. For example, ADO Recordsets only become filled or usable through a method of the Connection object. A File object only becomes valid through the OpenFile method of a FileSystemObject object (never name your object object).
What theory governs this type of "structure" and what term is used to refer to this? I'm assuming this is something different from base classes and inheritance. Is this type of hierarchy something I'm likely to need to use when creating my own business logic and data access layer classes when database programming in .NET?
There are various Object creation Design Patterns, these are addressing the kind of relationship you're talking about. A really simple such pattern is the Factory pattern.
FileSystem {
File openFile(String path);
}
The FileSystem is a creator, or Factory for Files.
I do find it helpful to separate these two strands of thinking: what can this object do? Where do I get one of those objects.
To address your comment to your question:
Some of this will come with experience. The guiding principle is to have each class do one job well.
You begin to notice that certain pieces of code don't belong in the class being created (for example it's about lots of files not just one file) nor does it belong in the class that wants to use the created class, because then the code would potentially be duplicated across many pieces of code (anyone who wants a file) so there's a need to give responsibility to some class. Aha that's a Factory.
You are talking about Factory Design Pattern.
Factories are useful when you need to abstract away logic of objection creation from the functionality of the object itself.
Edit: Seems it does have a name, go with the other answers..
There's no real name for it, what happens that the method you call returns a certain object, wich is of the type you wanted to have (IE the OpenFile method returns an object of type File).
Usually in .Net there are more ways you can get an instance of a certain type, the easiest is just saying SomeClass myInstance = new SomeClass();
to new up an object.
The pattern you describe exists too, for instance FolderInfo.GetFiles() returns an array of FileInfo objects.
So there's no real theory governing this, it's just basic Object Oriented programming. (Or that would be the governing theory).
GJ
精彩评论