views:

89

answers:

1

Hi @all,

I have a class hierarchy / inheritance like this:

public class A {
    private String name;
    // with getters &  setters
    public void doAWithName(){
        ...
    }
}

public class B extends A {
    public void doBWithName(){
        // a differnt implementation to what I do in class A
    }
}

public class C extends B {
    public void doCWithName(){
        // a differnt implementation to what I do in class A and B
    }
}

So at one time there is a instance of class A with the initialized field "name". Later I want this instance of A get wrapped into instance of B or C. So the superclasses should be get wrapped with a subclass!

How can I make this most efficent with respect to DRY?
I've thought about a constructor that does some copying with the getters/setters. But in this case I have to repeat myself - and this doesn't respect anymore to my initial requirement of DRY!

So, how can I warp A to B by just initializing B's new fields (with default values) and delegating the rest to a method in A (which knows more than B about which fields of A should be accessed...).

In the same way:
If A should be wrapped into C only a method in c should init C's 'new' fields, delegate to B's wrap method (which therefore inits B's 'new' fields in C) and at last B delegates to A which copies it's fields to the fields of C).

So in the end I have a new instance of C which has the values of A wrapped (and some default init values to the fields which the inheritance hierarchy has added).

+2  A: 

It seems that you just want to implement a Decorator Pattern.

Roman
But doesn't this mean to rewrite all getters/setters from the superclass? I mean to delegate the calls to the superclass. I.e. assuming a property name in class A (with getName/setName), so when using the DecoratorPattern class B doesn't extend class A. B only gets a reference of A as parameter of B's constructor. So, to call A's getName() method B needs to have a method "getName()", which delegates this call to the instance of A (which B i.e. has stored as a private field: like: return this.instanceOfA.getName() ).
gerry