架构师训练营第三章作业

用户头像
饶军
关注
发布于: 2020 年 06 月 24 日

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



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

// 抽像组件类

public abstract class Widget {

private String type = ""; //组件类型

private String name = ""; //组件名称

public Widget(String type, String name) {

this.type = type;

this.name = name;

}

//输出组件信息

public String getInfo(){

String info = "";

info = "print " + this.type + "(" + this.name + ")";

return info;

}



}



//树叶节点

public class Leaf extends Widget {



public Leaf(String type, String name) {

super(type, name);

}



}



import java.util.ArrayList;

//树枝节点

public class Branch extends Widget {



ArrayList<Widget> subList = new ArrayList<Widget>();

public Branch(String type, String name) {

super(type, name);

}



//增加子节点

public void addSub(Widget widget){

this.subList.add(widget);

}

//获得所有子节点

public ArrayList<Widget> getSub(){

return this.subList;

}

}



import java.util.ArrayList;

//场景测试类

public class Client {



//打印树的内容

public static String getTreeInfo(Branch root) {

ArrayList<Widget> subList = root.getSub();

String info = "";

for (Widget w : subList) {

if (w instanceof Leaf) { //叶子节点

info = info + w.getInfo() + "\n";

}

if(w instanceof Branch){ //树枝节点,打印本身及自身树的内容

info = info + w.getInfo() + "\n" + getTreeInfo((Branch)w);

}



}

return info;

}



public static void main(String[] args) {

Branch winForm = new Branch("WinForm", "WINDOW窗口");

Branch frame1 = new Branch("Frame", "FRAME1");

Leaf logo = new Leaf("Picture", "LOGO图片");

Leaf logon = new Leaf("Button", "登录");

Leaf regist = new Leaf("Button", "注册");

Leaf userName = new Leaf("Label", "用户名");

Leaf userNameText = new Leaf("TextBox", "文本框");

Leaf passwd = new Leaf("Label", "密码");

Leaf passwdText = new Leaf("PasswordBox", "密码框");

Leaf checkBox = new Leaf("CheckBox", "复选框");

Leaf remember = new Leaf("TextBox", "记住用户名");

Leaf forgetPasswd = new Leaf("LinkLable", "忘记密码");



winForm.addSub(logo);

winForm.addSub(logon);

winForm.addSub(regist);

winForm.addSub(frame1);

frame1.addSub(userName);

frame1.addSub(userNameText);

frame1.addSub(passwd);

frame1.addSub(passwdText);

frame1.addSub(checkBox);

frame1.addSub(remember);

frame1.addSub(forgetPasswd);



//打印根节点

System.out.println(winForm.getInfo());

//打印树枝及树叶

System.out.println(getTreeInfo(winForm));



}



}



用户头像

饶军

关注

还未添加个人签名 2020.03.23 加入

还未添加个人简介

评论

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