1 Reply Latest reply on Oct 12, 2011 10:34 AM by TPD-Opitz

    Alternative to decorator Pattern

      I am new to this forum, so first I would like to greet all of you.
      During my programming job I encountered the following problem:

      I have following class hierarchy

      I-- A -- AwithFeature1
      I-- B -- BwithFeature1
      I-- C -- CwithFeature1
      I-- D (D has no subclass with feature1)

      where {A,B,C}withFeature1 overrides some methods in ROOT.

      I would like to add new feature in the future to clases A..D but without having to extend the hierarchy to something like this :

      I-- A -- AwithFeature1-- AwithFeature1And2
      I-- B -- BwithFeature1-- BwithFeature1And2
      I-- C -- CwithFeature1-- CwithFeature1And2
      I-- D -- DwithFeature2

      In order to reduce the number of classes i have tried to define decorator pattern on class ROOT like:

      class Wrapper extends ROOT {
      ROOT wrappedObject;
      public Wrapper(ROOT wrappedObject) {
      this.wrappedObject = wrappedObject;
      //plenty of delegate methods

      public static ROOT decorateWithFeature1(ROOT toBeWrappedObject) {
      return new Wrapper(toBeWrappedObject) {

      void methodToOverride() {
      //feature1 specific code

      but in that case I am losing the access to non public, class specific methods that are not defined in ROOT (there are plenty of them in subclasses A..C).

      Is there any possibility (design pattern) to extend the fuctionality of classes A...C with FeaturesXYZ without having to subclass in every case ?

      Best regards

        • 1. Re: Alternative to decorator Pattern
          Welcome to the forum!

          The question that comes to my mind is:
          How will featur2 work with class D which seams not to have the non public methods of classes A - C?

          I'd suggest that you closely look at your existing classes if you can split them into smaller ones. Especially I'd try to extract Featur1 so that it has the same interface as Feature2. Than I'd compose the features with the smaller pieces.

          This way your instances of Root could just hold a collection of features and simply iterate over it to invoke the features. Root would not need subclasses because of the features (but maybe for other reasons...).