开发者

Layering functionality using inheritance?

开发者 https://www.devze.com 2023-03-25 11:11 出处:网络
I’ve got a Recorder class. It can record scenes, audio and music. The precise details of the recording process are not interesting – for example scene recording requires several instance variables a

I’ve got a Recorder class. It can record scenes, audio and music. The precise details of the recording process are not interesting – for example scene recording requires several instance variables and the API looks like this:

- (void) startRecordingScene: (Scene*) scene;
- (void) stopRecordingCurrentScene;

The same goes for audio and music. What I don’t lik开发者_JS百科e about the class is that it’s really three classes – one for recording scenes, one for audio and one for music. I’d like to split the class, but I’m not sure how. This is Objective-C, so that I could use categories, but those cannot add new instance variables.

What do you think about layering the functionality using inheritance? Like having SceneRecorder, AudioRecorder, and MusicRecorder, each inheriting from the previous one. This feels like misusing inheritance. The three are related, but I can’t really say that AudioRecorder is a SceneRecorder. I could call them AudioRecorder, AudioAndSceneRecorder etc., but that’s a mess.

How about composition? All three components need to share some data, like the recording itself or the information about last recording event. So composition does not seem to fit the bill either.

How would you go about such design?


Music is clearly a subset of Audio, so a MusicRecorder could be a subclass of an AudioRecorder. A scene is probably video and audio? There is no multiple inheritance in Obj-C, but I guess a scene is not separate audio and video anyway, so both should be subclasses of Recorder.

You can get rid of the entire mess and only expose Recorder, which is the visible part of a class cluster. The various classes that make up the cluster are kept private. That way you can combine at will. Just make sure your Recorder class exposes all possibilities:

-(id) initWithMusic:(Music *)music; // returns MusicRecorder
-(id) initWithScene:(Scene *)scene; // returns SceneRecorder

etc. Internally, your design can make use of hierarchies where it makes sense, while externally, there is only one class. The best of both worlds, IMO.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号