架构师训练营第 03 周—— 练习
发布于: 2020 年 06 月 24 日

作业一:
请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。
 
 作业二:
请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。
 
 组件接口代码
public interface Component {
    /**
     * 输出组件名称
     */
    void print();
}复制代码
 容器代码
public class Container implements Component {
    /**
     * 保存容器内的组件
     */
    private final List<Component> list = new ArrayList<>();
    private final String name;
    public Container(String name) {
        this.name = name;
    }
    
    public void add(Component component) {
        list.add(component);
    }
    @Override
    public void print() {
        System.out.println(name);
        for (Component component : list) {
            component.print();
        }
    }
}复制代码
 元素代码
public class Element implements Component {
    private final String name;
    public Element(String name) {
        this.name = name;
    }
    @Override
    public void print() {
        System.out.println(name);
    }
}复制代码
 测试代码
public class Test {
    public static void main(String[] args) {
        Container winForm = new Container("WinForm(WINDOW窗口)");
        Element picture = new Element("Picture(LOGO图片)");
        Element loginButton = new Element("Button(登录)");
        Element regButton = new Element("Button(注册)");
        winForm.add(picture);
        winForm.add(loginButton);
        winForm.add(regButton);
        Container frame = new Container("Frame(FRAME1)");
        Element userLabel = new Element("Label(用户名)");
        Element textBox = new Element("TextBox(文本框)");
        Element passLabel = new Element("Label(密码)");
        Element passBox = new Element("PasswordBox(密码框)");
        Element checkBox = new Element("CheckBox(复选框)");
        Element textBox2 = new Element("TextBox(记住用户名)");
        Element linkLabel = new Element("LinkLabel(忘记密码)");
        frame.add(userLabel);
        frame.add(textBox);
        frame.add(passLabel);
        frame.add(passBox);
        frame.add(checkBox);
        frame.add(textBox2);
        frame.add(linkLabel);
        winForm.add(frame);
        winForm.print();
    }
}复制代码
 输出结果
WinForm(WINDOW窗口)Picture(LOGO图片)Button(登录)Button(注册)Frame(FRAME1)Label(用户名)TextBox(文本框)Label(密码)PasswordBox(密码框)CheckBox(复选框)TextBox(记住用户名)LinkLabel(忘记密码)复制代码
 划线
评论
复制
发布于: 2020 年 06 月 24 日阅读数: 75

李伟
关注
还未添加个人签名 2018.05.07 加入
还未添加个人简介











 
    
评论