架构师训练营 - 作业 - 第三周

发布于: 2020 年 06 月 23 日

请在草稿纸上手写一个单例模式的实现代码

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

组合模式

定义

又叫部分-整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分及整体层次。这种类型的设计模式属于结构性模式,它创建了对象组的树形结构。实现组合模式使得客户端对单个对象和组合对象的使用具有一致性。

Wikipedia Definition

The composite pattern describes a group of objects that are treated as the same way as a single instance of the same type of the object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

UML Class Diagram

示例代码

  1. Interface - Component

  2. Implementation - Control(Picture/Button/Label/TextBox/PasswordBox/CheckBox/LinkLabel)

  3. Implementation - Container(WinForm/Frame)

import java.util.ArrayList;
interface Component {
public void print();
}
class Control implements Component {
private String name;
public Control(String name) {
this.name = name;
}
@Override
public void print() {
System.out.println("print" + " " + this.name);
}
}
class Container implements Component {
private String name;
private final ArrayList<Component> list = new ArrayList<>();
public Container(String name) {
this.name = name;
}
public void add(Component c) {
list.add(c);
}
@Override
public void print() {
System.out.println("print" + " " + this.name);
for (Component component : list) {
component.print();
}
}
}
class PrintWinForm {
public static void main(String[] args) {
Container winForm = new Container("WinForm(WINDOW窗口)");
Control picture = new Control("Picture(LOGO图片)");
Control btnLogin = new Control("Button(登录)");
Control btnReg = new Control("Button(注册))");
Container frame = new Container("Frame(FEAME1)");
winForm.add(picture);
winForm.add(btnLogin);
winForm.add(btnReg);
winForm.add(frame);
Control lblUsername = new Control("Label(用户名)");
Control txtUsername = new Control("TextBox(文本框)");
Control lblPassword = new Control("Label(密码)");
Control txtPassword = new Control("PasswordBox(密码框)");
Control chkRememberPassword = new Control("CheckBox(复选框)");
Control lblRememberPassword = new Control("TextBox(记住用户名)");
Control lblForgotPassword = new Control("LinkLabel(忘记密码)");
frame.add(lblUsername);
frame.add(txtUsername);
frame.add(lblPassword);
frame.add(txtPassword);
frame.add(chkRememberPassword);
frame.add(lblRememberPassword);
frame.add(lblForgotPassword);
winForm.print();
}
}

Reference

https://en.wikipedia.org/wiki/Composite_pattern

用户头像

心在飞

关注

还未添加个人签名 2017.10.15 加入

2个女儿的爸爸 | 程序员 | CS 反恐精英

评论

发布
暂无评论
架构师训练营 - 作业 - 第三周