package structure;
import java.util.ArrayList;
import java.util.List;
interface Item {
void print();
String getName();
void setName(String name);
List<Item> getChilds();
int addChild(Item item);
}
abstract class Component implements Item {
private List<Item> childs = new ArrayList<>();
private String name;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public List<Item> getChilds() {
return childs;
}
@Override
public void print() {
String className = this.getClass().getSimpleName();
System.out.println("print " + className + "(" + getName() + ")");
List<Item> childs = getChilds();
for (Item item: childs) {
item.print();
}
}
@Override
public int addChild(Item item) {
List<Item> childs = getChilds();
if (childs == null) {
return 0;
}
if (item != null) {
childs.add(item);
}
return childs.size();
}
}
class WinForm extends Component { }
class Button extends Component { }
class CheckBox extends Component { }
class Frame extends Component { }
class Label extends Component { }
class LinkLabel extends Component { }
class PasswordBox extends Component { }
class Picture extends Component { }
class TextBox extends Component { }
public class Composition {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Item mainForm = createChild("WINDOW窗口", WinForm.class);
addChilds(mainForm);
mainForm.print();
}
static <T> Item createChild(String name, Class<T> clazz) throws IllegalAccessException, InstantiationException {
Item child = (Item)clazz.newInstance();
child.setName(name);
return child;
}
static void addChilds(Item mainForm) throws InstantiationException, IllegalAccessException {
mainForm.addChild(createChild("LOGO图片", Picture.class));
mainForm.addChild(createChild("登录", Button.class));
mainForm.addChild(createChild("注册", Button.class));
Item frame = createChild("FRAME1", Frame.class);
mainForm.addChild(frame);
frame.addChild(createChild("用户名", Label.class));
frame.addChild(createChild("文本框", TextBox.class));
frame.addChild(createChild("密码", Label.class));
frame.addChild(createChild("密码框", PasswordBox.class));
frame.addChild(createChild("复选框", CheckBox.class));
frame.addChild(createChild("记住用户名", TextBox.class));
frame.addChild(createChild("忘记密码", LinkLabel.class));
}
}
评论