架构师训练营 - 第 3 周课后作业(1 期)
1. 请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。
2. 请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。
public class Component {
private String type;
private String desc;
private List<Component> subComponents;
public Component(String type, String desc) {
this.type = type;
this.desc = desc;
this.subComponents = new ArrayList<>();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void add(Component e) {
subComponents.add(e);
}
public void remove(Component e) {
subComponents.remove(e);
}
public List<Component> getSubComponents() {
return subComponents;
}
@Override
public String toString() {
return type + "(" + desc + ")";
}
}
public class WindowMain {
public static void main(String[] args) {
Component wf = new Component("WinForm", "WINDOW窗口");
Component pct = new Component("Picture", "LOGO图片");
Component btn1 = new Component("Button", "登陆");
Component btn2 = new Component("Button", "注册");
wf.add(pct);
wf.add(btn1);
wf.add(btn2);
Component frame = new Component("Frame", "FRAME1");
Component lb1 = new Component("Lable", "用户名");
Component tbx1 = new Component("TextBox", "文本框");
Component lb2 = new Component("Lable", "密码");
Component pbx = new Component("PasswordBox", "密码框");
Component cbx = new Component("CheckBox", "复选框");
Component tbx2 = new Component("TextBox", "记住密码");
Component lklb = new Component("LinkLable", "忘记密码");
frame.add(lb1);
frame.add(tbx1);
frame.add(lb2);
frame.add(pbx);
frame.add(cbx);
frame.add(tbx2);
frame.add(lklb);
wf.add(frame);
System.out.println(wf);
for (Component cp : wf.getSubComponents()) {
System.out.println(cp);
for (Component scp : cp.getSubComponents()) {
System.out.println(scp);
}
}
}
}
评论