架构师训练营第 3 周课后练习

用户头像
叶纪想
关注
发布于: 2020 年 10 月 04 日

题目

1. 请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。

2. 请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。



解答

1.

2.

public interface Component {
void print();
}



public class Window implements Component{
private List<Component> subComponents = new ArrayList<>();
@Override
public void print() {
System.out.println("print WinForm(WINDOW窗口)");
for (Component subComponent : subComponents) {
subComponent.print();
}
}
public void addNode(Component component){
subComponents.add(component);
}
}



public class Picture implements Component{
@Override
public void print() {
System.out.println("print Picture(LOGO图片)");
}
}



public class Button implements Component {
private String text;
public Button(String text) {
this.text = text;
}
@Override
public void print() {
System.out.println("print Button(" + text + ")");
}
}



public class Frame implements Component{
private List<Component> subComponents = new ArrayList<>();
@Override
public void print() {
System.out.println("print Frame(FRAME1)");
for (Component subComponent : subComponents) {
subComponent.print();
}
}
public void addNode(Component component){
subComponents.add(component);
}
}



public class Label implements Component {
private String text;
public Label(String text) {
this.text = text;
}
@Override
public void print() {
System.out.println("print Label(" + text + ")");
}
}



public class TextBox implements Component{
@Override
public void print() {
System.out.println("print TextBox(文本框)");
}
}



public class PasswordBox implements Component{
@Override
public void print() {
System.out.println("print PasswordBox(密码框)");
}
}



public class CheckBox implements Component{
@Override
public void print() {
System.out.println("print CheckBox(复选框)");
}
}



public class LinkLable implements Component {
private String text;
public LinkLable(String text) {
this.text = text;
}
@Override
public void print() {
System.out.println("print LinkLable(" + text + ")");
}
}



public class Main {
public static void main(String[] args) {
Window window = new Window();
window.addNode(new Picture());
window.addNode(new Button("登录"));
window.addNode(new Button("注册"));
Frame frame = new Frame();
frame.addNode(new Label("用户名"));
frame.addNode(new TextBox());
frame.addNode(new Label("密码"));
frame.addNode(new PasswordBox());
frame.addNode(new CheckBox());
frame.addNode(new Label("记住用户名"));
frame.addNode(new LinkLable("忘记密码"));
window.addNode(frame);
window.print();
}
}



用户头像

叶纪想

关注

还未添加个人签名 2018.05.23 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营第 3 周课后练习