Search code examples
javadesign-patternsdecoratorbridge

in a dilemma about which to use decorator vs bridge pattern


I am confused about which pattern to use to design the following scenario,

Interface GearBox {
   int upshift();
   int downshift();
   int reverse();
}

AutoGearBox implements GearBox{...}
ManualGearBox implements GearBox{...}

Now I want to add DualClutchGearBox to the hierarchy.All previous gearboxes are single clutch. How do I go about doing it?

With Decorator -->

DualClutchDecorator implements GearBox{
     DualClutchDecorator(GearBox box){...}
}

With Bridge -->

GearBox{
   GearBoxImpl impl;
   ....
}

AutoGearBox implements GearBox{...}
ManualGearBox implements GearBox{...}

abstract class GearBoxImpl{}
SingleClutchImpl extends GearBoxImpl{...}
DualClutchImpl extends GearBoxImpl{...}

Which is one is better and why?


Solution

  • I'm not sure I'd use either of these patterns. Is there a reason why you don't want to just create a 3rd concrete class?

    You use Decorator when you need to dynamically change behavior. One of the main examples I can think of is Java's InputStreamReader. I can compose a decorated reader for whatever case I need and they conform to the same interface

    // I need to read lines from a file
    Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    
    // Or I want to read lines from a byte array and track the line numbers
    Reader r = new LineNumberReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
    

    So the idea of decorator is that I can change the behavior at runtime by adding decorators. This is not what you are trying to do from what I understand. A DualClutch will exhibit a specific behavior, there will be no need to change it on the fly.

    I don't see a great case from Bridge either but I guess it depends on your specific case. Like I said, it seems like DualClutch will just have static behavior and an automobile will either have it or not. Seems like a simple concrete class would do the trick.