下面的代码,给出了一个Composite模式简单的Java实现:
public abstract class Component{
public abstract void operation();
public void add(Component component){};
public void remove(Component component){};
}
import java.util.*;
public class Composite extends Component{
String name;
ArrayList children = new ArrayList();
public Composite(String name){
this.name = name;
}
public void add(Component component){
children.add(component);
}
public void remove(Component component){
children.remove(component);
}
public void operation(){
System.out.println(name);
Iterator iterator = children.iterator();
while(iterator.hasNext()){
Component child = (Component)iterator.next();
child.operation();
}
}
}
public class Leaf extends Component{
String name;
public Leaf(String name){
this.name = name;
}
public void operation(){
System.out.println(name);
}
}
Strategy模式
文章来源于领测软件测试网 https://www.ltesting.net/