week3 作业一

发布于: 23 小时前
week3作业一

封面:杭州白马湖公园

一、手写单例代码

二、使用组合模式遍历一棵树

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

类图:
代码示例:

画图接口:

public interface Draw {
void draw();
}

支持画图的叶子节点:

public class LeafNode implements Draw {
private String name;
// type不同,可能带来其他诸如渲染效果的不同,具体功能应当使用策略模式优化设计,这里仅打印
private String type;
public LeafNode(String name, String type) {
this.name = name;
this.type = type;
}
public void draw() {
System.out.println("print "+this.type+"("+this.name+")");
}
}

支持画图的树枝节点:

public class BranchNode implements Draw {
private LeafNode leafNode;
private List<? extends Draw> children;
public BranchNode(LeafNode leafNode, List<? extends Draw> children) {
this.leafNode = leafNode;
this.children = children;
}
public void draw() {
leafNode.draw();
for (Draw child : children) {
child.draw();
}
}
}

运行示例:

public static void main(String[] args) {
// init
LeafNode logo = new LeafNode("LOGO图片","Picture");
LeafNode login = new LeafNode("登陆","Button");
LeafNode register = new LeafNode("注册","Button");
LeafNode username = new LeafNode("用户名","Label");
LeafNode text_box = new LeafNode("文本框","TextBox");
LeafNode password_label = new LeafNode("密码","Label");
LeafNode password_box = new LeafNode("密码框","PasswordBox");
LeafNode check_box = new LeafNode("复选框","CheckBox");
LeafNode remember_me = new LeafNode("记住用户名","TextBox");
LeafNode forget_password = new LeafNode("忘记密码","LinkLabel");
BranchNode FRAME1 =
new BranchNode(new LeafNode("FRAME1","Frame"),Arrays.asList(username, text_box, password_label, password_box,check_box,remember_me,forget_password));
BranchNode window = new BranchNode(new LeafNode("WINDOW窗口","WinForm"), Arrays.asList(logo, login, register, FRAME1));
// draw
window.draw();
}

运行结果:

发布于: 23 小时前 阅读数: 4
用户头像

任鑫

关注

还未添加个人签名 2018.05.26 加入

还未添加个人简介

评论

发布
暂无评论
week3作业一