1

I am implementing my first Decorator pattern. The base class which I want to decorate has a member variable initialized in the constructor. The decorated class also has this member variable (since it is a descendant of the base class). My question is, should I initialize this member variable in the decorated class too, or use the member variable of the base class (which lives inside the decorated class)?

Here is some code. I'm just curious whether Decorated1 or Decorated2 is better?

public class Base{
private String memberVariable;
public Base(){
    memberVariable = "";
}
public Base(String s){
    memberVariable = s;
}
public String Description(){
    //code here
}
}

public abstract class BaseDecorator(){
public abstract String Description();
}

public class Decorated1 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
    b = _b;
}
public String Description(){
    //code here
}
public String getMemberVariable(){
    return b.getMemberVariable();
}
}

public class Decorated2 extends BaseDecorator{
Base b;
public Decorated1(Base _b){
    super(_b.getMemberVariable());
    b = _b;
}
public String Description(){
    //code here
}
public String getMembervariable(){
    return memberVariable;
}
}
robogos
  • 131
  • 1
  • 8

1 Answers1

0

You have to figure out what this variable means for your class, or if it is really needed, but i would suggest that no.

interface IObject{
    //declare methods
    void doSomething();
}

class ObjectA implements IObject{
    private int variable;
    public void doSomething(){
    }
}

class DecorateObject implements IObject {
    private IObject decoratedObject;
    public void doSomething(){
         decoratedObject.doSomething();
         //do more things
    }
}

if IObject is a drawable element, it would have x,y coordinates that would be inherited so it is correct to put on a superclass, in this case it would be an abstract class.

interface IObject{
    //declare methods
}

abstract class AbstractObject implements IObject{
    private int xCoordinate;
}

class ObjectA extends AbstractObject {

}

class DecorateObject extends AbstractObject {
    private IObject decoratedObject;
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
RamonBoza
  • 8,898
  • 6
  • 36
  • 48