架构师训练营第 1 期第 3 周作业
发布于: 2020 年 09 月 29 日

1. 请在草稿纸上手写一个单例模式的实现代码。
解:
方式1:预加载模式:

方式2:懒加载模式:

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


解:
类图如下:

Component接口:
public interface Component { public void add(Component c); public void remove(Component c); public Component getChild(int i); public void operation();}
Composite实现类:
package org.luchengye.combo;import java.util.ArrayList;public class Composite implements Component{ private ArrayList<Component> children = new ArrayList<Component>(); private String name; public Composite(String name) { this.name = name; } @Override public void add(Component c) { children.add(c); } @Override public void remove(Component c) { children.remove(c); } @Override public Component getChild(int i) { return children.get(i); } @Override public void operation() { System.out.println("print "+name); for (Object obj : children) { ((Component) obj).operation(); } }}
Leaf实现类:
package org.luchengye.combo;public class Leaf implements Component{ private String name; public Leaf(String name) { this.name = name; } @Override public void add(Component c) { } @Override public void remove(Component c) { } @Override public Component getChild(int i) { return null; } @Override public void operation() { System.out.println("print "+name); }}
Client主程序:
package org.luchengye.combo;public class Client { public static void main(String[] args) { Component component=new Composite("WinFrom(WINDOW窗口)"); component.add(new Leaf("Picture(LOGO图片)")); component.add(new Leaf("Button(登录)")); component.add(new Leaf("Button(注册)")); Component frame=new Composite("Frame(FRAME1)"); frame.add(new Leaf("Lable(用户名)")); frame.add(new Leaf("TextBox(文本框)")); frame.add(new Leaf("Lable(密码)")); frame.add(new Leaf("PasswordBox(密码框)")); frame.add(new Leaf("CheckBox(复选框)")); frame.add(new Leaf("TextBox(记住用户名)")); frame.add(new Leaf("LinkLable(忘记密码)")); component.add(frame); component.operation(); }}
输出结果:

划线
评论
复制
发布于: 2020 年 09 月 29 日阅读数: 42

业哥
关注
架构即未来! 2018.02.19 加入
还未添加个人简介
评论