架构师训练营第三周 - 作业
发布于: 2020 年 06 月 22 日
1 请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。
2 请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3
代码如下:
package com.example;
public abstract class Component {
private String name;
public Component(String name) {
this.name = name;
}
public void print () {
System.out.println(String.format("%s(%s)", this.getClass().getSimpleName(), name));
}
}
复制代码
package com.example;
import java.util.ArrayList;
import java.util.List;
public abstract class Container extends Component{
private List<Component> children = new ArrayList<Component>();
public Container(String name) {
super(name);
}
public void addChild(Component c) {
children.add(c);
}
public void print () {
super.print();
for (Component child : children) {
child.print();
}
}
}
复制代码
package com.example;
public class WindowForm extends Container {
public WindowForm(String name) {
super(name);
}
}
复制代码
package com.example;
public class Frame extends Container {
public Frame(String name) {
super(name);
}
}
复制代码
package com.example;
public class Button extends Component {
public Button (String name) {
super(name);
}
}
复制代码
package com.example;
public class CheckBox extends Component {
public CheckBox(String name) {
super(name);
}
}
复制代码
package com.example;
public class Label extends Component{
public Label(String name) {
super(name);
}
}
复制代码
package com.example;
public class LinkLabel extends Component {
public LinkLabel(String name) {
super(name);
}
}
复制代码
package com.example;
public class PasswordBox extends Component {
public PasswordBox(String name) {
super(name);
}
}
复制代码
package com.example;
public class Picture extends Component {
public Picture(String name) {
super(name);
}
}
复制代码
package com.example;
public class TextBox extends Component {
public TextBox(String name) {
super(name);
}
}
复制代码
package com.example;
public class Main {
public static void main(String[] args) {
// create WindowForm
WindowForm windowForm = new WindowForm("WINDOW窗口");
windowForm.addChild(new Picture("LOGO图片"));
windowForm.addChild(new Button("登录"));
windowForm.addChild(new Button("注册"));
// create Frame
Frame frame = new Frame("FRAME1");
frame.addChild(new Label("用户名"));
frame.addChild(new TextBox("文本框"));
frame.addChild(new Label("密码"));
frame.addChild(new PasswordBox("密码框"));
frame.addChild(new CheckBox("记住用户名"));
frame.addChild(new LinkLabel("忘记密码"));
windowForm.addChild(frame);
// print
windowForm.print();
}
}
复制代码
运行结果:
划线
评论
复制
发布于: 2020 年 06 月 22 日阅读数: 54
Eric
关注
给写代码的人写代码 2017.10.17 加入
Clojure
评论