Javaで単純なデコレータパターンを実装しようとしました。主なアイデアは、具体的なデコレータが基本リストに何かを追加する必要があるということです。ただし、私の実装は正しく機能せず、その理由はわかりません。
出力は次のようになります。
ING -1,ING 0,ING 1.
しかし、それは次のようになります。
ING -1,ING 0,ING 1, ING 2.
これが私のコードです:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.util.ArrayList;
import java.util.List;
abstract class Tester {
protected List<String> ingridients = new ArrayList();
protected String description;
public String getDescription() {
description = "";
for (String i : ingridients) {
description += i;
description += ",";
}
description = description.substring(0, description.length() - 1);
description += ".";
return description;
}
}
abstract class Decorator extends Tester {
@Override
public abstract String getDescription();
}
class Test1 extends Tester {
public Test1() {
this.ingridients.add("ING -1");
this.ingridients.add("ING 0");
}
}
class Ing1 extends Decorator {
private Tester t;
public Ing1(Tester t) {
this.t = t;
}
@Override
public String getDescription() {
this.t.ingridients.add("ING 1");
return this.t.getDescription();
}
}
class Ing2 extends Decorator {
private Tester t;
public Ing2(Tester t) {
this.t = t;
}
@Override
public String getDescription() {
this.t.ingridients.add("ING 2");
return this.t.getDescription();
}
}
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Tester t = new Test1();
t = new Ing1(t);
t = new Ing2(t);
System.out.println(t.getDescription());
}
}
編集されたコード:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.util.ArrayList;
import java.util.List;
interface Tester {
List<String> ingridients = new ArrayList();
public String getDescription();
}
abstract class Decorator implements Tester {
@Override
public abstract String getDescription();
}
class Test1 implements Tester {
public Test1() {
ingridients.add("ING -1");
ingridients.add("ING 0");
}
@Override
public String getDescription() {
String description = "";
for (String i : ingridients) {
description += i;
description += ",";
}
description = description.substring(0, description.length() - 1);
description += ".";
return description;
}
}
class Ing1 extends Decorator {
private Tester t;
public Ing1(Tester t) {
this.t = t;
}
@Override
public String getDescription() {
this.t.ingridients.add("ING 1");
return this.t.getDescription();
}
}
class Ing2 extends Decorator {
private Tester t;
public Ing2(Tester t) {
this.t = t;
}
@Override
public String getDescription() {
this.t.ingridients.add("ING 2");
return this.t.getDescription();
}
}
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Tester t = new Test1();
t = new Ing1(t);
t = new Ing2(t);
System.out.println(t.getDescription());
}
}