The question is if you need a factory. factory is designed to control instantiation not so much for the behavior of related instances.
Otherwise, you are just looking at basic inheritance. Something like..
class Actor{ public void act(){ System.out.println("I act.."); } } class StuntActor extends Actor { public void act(){ System.out.println("I do fancy stunts.."); } } class VoiceActor extends Actor { public void act(){ System.out.println("I make funny noises.."); } }
To use, you can simply create an instance of the type that you need directly.
Actor fred = new Actor(); Actor tom = new VoiceActor(); Actor sally = new StuntActor(); fred.act(); tom.act(); sally.act();
Output:
I act.. I make funny noises.. I do fancy stunts..
EDIT:
If you need to centralize the creation of Actors..aka in relation to Factory, you will not be able to get away from some kind of switching logic - in this case ... I usually use an enumeration for readability:
public class Actor{ public enum Type{ REGULAR, VOICE, STUNT } public static Actor Create(Actor.Type type){ switch(type) { case VOICE: return new VoiceActor(); case STUNT: return new StuntActor(); case REGULAR: default: return new Actor(); } } public void act(){ System.out.println("I act.."); } }
Using:
Actor some_actor = Actor.Create(Actor.Type.VOICE); some_actor.act();
Output:
I make funny noises..
ltiong_sh
source share