架构师训练营第 2 期 - 第 3 周作业 1
单例模式
请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。
package hello;
//组件基类
public abstract class Component {
private String name;
private Component() {}
public Component(String name) {
this.name = name;
}
protected void print() {
String type = this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1);
System.out.println("print " + type + "(" + name + ")");
};
}
//容器基类
public class Container extends Component {
List<Component> componentList = new ArrayList<>();
public Container(String name) {
super(name);
}
protected Container add(Component component) {
componentList.add(component);
return this;
}
@Override
public void print() {
super.print();
for (Component component : componentList) {
component.print();
}
}
}
public class Button extends Component {
public Button(String name) {
super(name);
}
}
public class CheckBox extends Component {
public CheckBox(String name) {
super(name);
}
}
public class Frame extends Container {
public Frame(String name) {
super(name);
}
}
public class Lable extends Component {
public Lable(String name) {
super(name);
}
}
public class LinkLable extends Lable {
public LinkLable(String name) {
super(name);
}
}
public class PasswordBox extends TextBox {
public PasswordBox(String name) {
super(name);
}
}
public class Picture extends Component {
public Picture(String name) {
super(name);
}
}
public class TextBox extends Component {
public TextBox(String name) {
super(name);
}
}
public class WinForm extends Container {
public WinForm(String name) {
super(name);
}
public static void main(String[] args) {
WinForm winForm = new WinForm("WINDOW 窗口");
winForm.add(new Picture("LOGO 图片"))
.add(new Button("登录"))
.add(new Button("注册"))
.add(new Frame("FRAME1")
.add(new Lable("用户名"))
.add(new TextBox("文本框"))
.add(new Lable("密码"))
.add(new PasswordBox("密码框"))
.add(new CheckBox("复选框"))
.add(new TextBox("记住用户名"))
.add(new LinkLable("忘记密码")))
.print();
}
}
评论