6

我正在阅读“傻瓜设计模式”。我阅读并练习了装饰器模式。使用装饰器模式,我们可以用任何东西装饰一个对象。现在,我想在装饰之前删除装饰对象。我已经通过 ArrayList 解决了这个问题,但我仍然觉得它不好。你能告诉我如何去除装饰物吗?还有什么更好的方法?

这是我的方式:

计算机.java

public class Computer {

    public Computer() {
    }

    public String description() {
        return "computer";
    }

}

组件装饰器.java

public abstract class ComponentDecorator extends Computer {
    @Override
    public abstract String description();
}

光盘.java

public class CD extends ComponentDecorator {
    private Computer computer;

    public CD() {
    }

    public CD(Computer computer) {
        this.computer = computer;
    }

    @Override
    public String description() {
        return computer.description() + " and a CD";
    }

}

磁盘.java

public class Disk extends ComponentDecorator {
    private Computer computer;

    public Disk() {
    }

    public Disk(Computer c) {
        computer = c;
    }

    @Override
    public String description() {
        return computer.description() + " and a disk";
    }

}

监视器.java

public class Monitor extends ComponentDecorator {
    private Computer computer;

    public Monitor() {
    }

    public Monitor(Computer computer) {
        this.computer = computer;
    }

    @Override
    public String description() {
        return computer.description() + " and a monitor";
    }

}

主.java

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    static ArrayList<ComponentDecorator> list = new ArrayList<>();

    public static void main(String[] args) {
        addComponent(new CD(), new Disk(), new Monitor());
        System.out.println(list.size());
        Computer penIII = getComputer();
        removeComponent(new Monitor());
        penIII = getComputer();
        System.out.println(penIII.description());
    }

    private static void addComponent(ComponentDecorator... comp) {
        list.addAll(Arrays.asList(comp));
    }

    private static void removeComponent(ComponentDecorator comp) {
        for(ComponentDecorator c : list) {
            if(c.getClass() == comp.getClass()) {
                list.remove(list.indexOf(c));
                break;
            }
        }
    }

    private static Computer getComputer() {
        Computer c = new Computer();
        Class e;
        for(ComponentDecorator d : list) {
            e = d.getClass();
            try {
                c = (Computer) e.getConstructor(new Class[]{Computer.class}).newInstance(c);
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
        return c;
    }
}
4

3 回答 3

10

更好的方法是将“removeDecorator”方法添加到您的 ComponentDecorator 类。

public abstract class ComponentDecorator {

private ComponentDecorator subject;

public ComponentDecorator(ComponentDecorator subject) {
  this.subject = subject;
}

@Override
public abstract String description();
}

public void removeDecorator(ComponentDecorator toRemove) {
  if (subject == null) {
    return;
  } else if (subject.equals(toRemove)) {
    subject = subject.getSubject();
  } else {
    subject.removeDecorator(toRemove);
  }
}

public ComponentDecorator getSubject() {
  return subject;
}


// Computer
public class Computer extends ComponentDecorator{

public Computer() {
  super(null);
}

public String description() {
  return "computer";
}

// CD
public class CD extends ComponentDecorator {

  public CD(ComponentDecorator computer) {
    super(computer);
  }

  @Override
  public String description() {
    return getSubject().description() + " and a CD";
  }
}

// main
public static void main(String[] args) {
    ComponentDecorator penIII = new Computer();
    penIII = new CD(penIII);
    penIII = new Monitor(penIII);
    System.out.println(penIII.description());
}

}

如果您没有要删除的装饰器的引用,您可以创建另一个类的方法来代替。

但是,您需要将装饰对象作为“ComponentDecorator”而不是“Computer”。我建议让 Computer 类扩展 ComponentDecorator 而不是相反。

于 2012-09-02T23:28:28.220 回答
1

我怀疑我误解了你的问题,但是要从装饰器中取出装饰的(内部)对象,你可以在装饰器中添加一个 get 方法。添加

public abstract Computer getDecorated();

到 ComponentDecorator 和

public Computer getDecorated(){return computer;}

到每个子类(CD,监视器,...)。那是你要找的吗?

于 2012-09-02T21:50:08.230 回答
1

向接口添加两个方法, undecorate() 和 removeDecoration(String className):

事物接口.java

public interface ThingInterface {
    public ThingInterface undecorate();
    public ThingInterface removeDecoration(String className);
    public String nonDecoratedString();
    public String decoratedString();
}

您的基类将简单地为这些方法返回自身:

BaseThing.java

public class BaseThing implements ThingInterface {

    private String basicString;

    public BaseThing(String string) {
        basicString = string;
    }

    @Override
    public ThingInterface undecorate() {
        return this;
    }

    @Override
    public ThingInterface removeDecoration(String className) {
        return this;
    }

    @Override
    public String nonDecoratedString() {
        return basicString;
    }

    @Override
    public String decoratedString() {
        return basicString;
    }

}

现在,您需要的真正内容在抽象类中:

AbstractThingDecorator.java

public abstract class AbstractThingDecorator implements ThingInterface {

    private ThingInterface thing;

    public AbstractThingDecorator(ThingInterface thing) {
        this.thing = thing;
    }

    @Override
    public ThingInterface removeDecoration(String className) {
        ThingInterface undecorate = this;
        if(this.getClass().getName() == className) {
            undecorate = this.undecorate();
        } 
        else {
            ArrayList<String> classStack = new ArrayList();
            while(undecorate != undecorate.undecorate()) {
                if(undecorate.getClass().getName() != className) {
                    classStack.add(undecorate.getClass().getName());
                }
                undecorate = undecorate.undecorate();
            }
            for(int i = classStack.size()-1;i == 0;i--) {
                try {
                    Class<?> clazz = Class.forName(classStack.get(i));
                    Constructor<?> ctor = clazz.getConstructor(ThingInterface.class);
                    Object object = ctor.newInstance(new Object[] { undecorate });      
                    undecorate = (ThingInterface) object;
                }
                catch(Exception e) {
                    System.out.println("Exception:" + e.getMessage());
                }
            }
        }
        return undecorate;
    }

    @Override
    public ThingInterface undecorate() {
        return this.thing;
    }

    @Override
    public String nonDecoratedString() {
        return thing.nonDecoratedString();
    }

    @Override
    public String decoratedString() {
        return thing.decoratedString();
    }

}

我添加了两个简单的装饰器,ThingDecorator 和 FancyThingDecorator:

ThingDecorator.java

public class ThingDecorator extends AbstractThingDecorator {
    public ThingDecorator(ThingInterface thing) {
        super(thing);
    }

    @Override
    public ThingInterface undecorate() {
        return super.undecorate();
    }

    @Override
    public String decoratedString() {
        return super.decoratedString() + ", decorated";
    }
}

FancyThingDecorator.java

public class FancyThingDecorator extends AbstractThingDecorator {
    public FancyThingDecorator(ThingInterface thing) {
        super(thing);
    }

    @Override
    public ThingInterface undecorate() {
        return super.undecorate();
    }

    @Override
    public String decoratedString() {
        return super.decoratedString() + ", fancy";
    }
}

最后,我的java main:

装饰器.java

public class Decorator {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ThingInterface thing = new BaseThing("Basic string");
        ThingInterface decorator = new ThingDecorator(thing);
        ThingInterface fancyDecorator = new FancyThingDecorator(thing);
        ThingInterface extraFancy = new FancyThingDecorator(new ThingDecorator(thing));
        ThingInterface undecorate = new FancyThingDecorator(new ThingDecorator(thing));

        System.out.println("Basic thing is: " + thing.decoratedString()+".");
        System.out.println("Decorated thing is: " + decorator.decoratedString()+".");
        System.out.println("Fancy thing is: " + fancyDecorator.decoratedString()+".");
        System.out.println("Decorated fancy thing is: " + extraFancy.decoratedString()+".");

        while(extraFancy.undecorate() != extraFancy) {
            extraFancy = extraFancy.undecorate();
            System.out.println("Rolling back decorations: " + extraFancy.decoratedString()+".");
        }

        System.out.println("Decoration chain before removal is: " + undecorate.decoratedString());
        System.out.println("Removing decoration for " + ThingDecorator.class.getName());
        undecorate = undecorate.removeDecoration(ThingDecorator.class.getName());
        System.out.println("Decoration chain after removal is: " + undecorate.decoratedString()+".");

    }

}

输出是:

基本的东西是:基本字符串。

装饰的东西是:基本字符串,装饰。

花哨的是:基本字符串,花哨。

装饰花哨的东西是:基本字符串,装饰,花哨。

回滚装饰:基本弦,装饰。

回滚装饰:基本字符串。

移除前的装饰链为:基本字符串、装饰、花式

移除 ThingDecorator 的装饰

去掉后的装饰链是:基本串,花式。

于 2017-07-23T00:04:12.377 回答