I have never used Factories before for the simple reason, I don't understand when I need them. I have been working on a little game in my spare time, and I decided to implement FMOD for the sound. I looked at a wrapper designed for OpenAL(different sound setup) a开发者_StackOverflow社区nd it looked something like...
SoundObject* SoundObjectManager* SoundObjectFactory*
The SoundObject was basically the instance of each sound object. The SoundObjectManager just manages all of these objects. This is straight forward enough and makes plenty of sense, but I don't get what the factory is doing or what it is used. I have been reading up on Factorys but still don't really get them.
Any help would be appreciated!
Think of Factory as a "virtual constructor". It lets you construct objects with a common compile time type but different runtime types. You can switch behavior simply by telling the Factory to create an instance of a different runtime type.
Factories are used when the implementation needs to be parametrized. FMOD is cross platform, it needs to decide what concrete implementation to give you for your platform. That is what the Factory is doing. There are two main Patterns Abstract Factory Pattern and Factory Method Pattern.
Hypothetical situation: I'm writing a sound library that I want to run on multiple platforms. I'll try to make as much of the code as possible be platform independent, but certainly some of it will need to change for Windows versus OSX versus Linux.
So I write all these different implementations, but I don't want the end user to have to make their program depend on Linux or Windows or whatever. I also don't want to maintain 4 different interfaces to my API. (Note these are just some of the reasons you might create a factory -- there are certainly other situations).
So I define this nice generic SoundObject
base class that defines all the methods the client gets to use. Then I make my LinuxSoundObject
, WindowsSoundObject
, and 5 others derive from SoundObject
. But I'm going to hide all these concrete implementations from the user and only provide them with a SoundObject
. Instead, you have to call my SoundObjectFactory
to grab what appears to you to be a plain old SoundObject
, but really I've chosen the correct runtime type for you and instantiated it myself.
2 years later, a new OS comes about and displaces Windows. Instead of forcing you to rewrite your software, I just update my library to support the new platform and you never see a change to the interface.
This is all pretty contrived, but hopefully you get the idea.
Factories isolate consumers of an interface from what runtime type (i.e. implementation) is really being used.
Factories can be used to implement inversion of control, and to separate instantiation code (the 'new's) from the logic of your components. This is helpful when you're writing unit tests since you may not want tested objects to create a bunch of other objects.
精彩评论