我正在阅读“傻瓜设计模式”。我阅读并练习了装饰器模式。使用装饰器模式,我们可以用任何东西装饰一个对象。现在,我想在装饰之前删除装饰对象。我已经通过 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;
}
}