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

发布于: 27 分钟前

作业一

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

作业二

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

抽象构件代码

package com.ocean;
/**
* 抽象构件
*/
public abstract class Component {
protected String name;
public Component(String name){
this.name = name;
}
public abstract void print();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Component component = (Component) o;
return name.equals(component.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}

树枝构件代码

package com.ocean;
import java.util.*;
/**
* 树枝构件
*/
public class Composite extends Component {
public Composite(String name) {
super(name);
}
/**
* 构件容器
*/
private Set<Component> components = new LinkedHashSet<>();
/**
* 增加一个叶子构件或分支构件
* @param component
*/
public void add(Component component){
this.components.add(component);
}
public void remove(Component component){
this.components.remove(component);
}
public Set<Component> getChilden(){
return this.components;
}
@Override
public void print() {
System.out.println("print " + this.name);
for(Component c : this.getChilden()){
c.print();
}
}
}

树叶构件代码

package com.ocean;
/**
* 树叶构件
*/
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void print() {
System.out.println("print " + this.name);
}
}

场景代码

package com.ocean;
public class Client {
public static void main(String[] args) {
Composite window = createWindow();
print(window);
}
public static Composite createWindow(){
Composite root = new Composite("WinForm(WINDOW窗口)");
root.add(new Composite("Picture(LOGO图片)"));
root.add(new Leaf("Button(登录)"));
root.add(new Leaf("Button(注册)"));
Composite formGroup = new Composite("Frame(FRAME1)");
formGroup.add(new Leaf("Label(用户名)"));
formGroup.add(new Leaf("TextBox(文本框)"));
formGroup.add(new Leaf("Label(密码)"));
formGroup.add(new Leaf("PasswordBox(密码框)"));
formGroup.add(new Leaf("CheckBox(复选框)"));
formGroup.add(new Leaf("TextBox(记住用户名)"));
formGroup.add(new Leaf("Label(忘记密码)"));
root.add(formGroup);
return root;
}
public static void print(Composite composite){
composite.print();
}
}

用户头像

桔子

关注

还未添加个人签名 2018.11.15 加入

还未添加个人简介

评论

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