第三周课后练习

用户头像
大大猫
关注
发布于: 2020 年 10 月 11 日

作业一

  1. 如下图所示:

  1. 代码如下所示:

interface IComponent {
add(c: IComponent);
remove(c: IComponent);
print();
}
abstract class Control implements IComponent {
add(c: IComponent) {
throw new Error("Method not implemented.");
}
remove(c: IComponent) {
throw new Error("Method not implemented.");
}
abstract print();
}
abstract class Container implements IComponent {
private _children = new Set<IComponent>();
add(c: IComponent) {
this._children.add(c);
}
remove(c: IComponent) {
this._children.delete(c);
}
print() {
this.printSelf();
this._children.forEach((c) => c.print());
}
abstract printSelf();
}
class Form extends Container {
printSelf() {
console.log("print WinForm");
}
}
class Frame extends Container {
printSelf() {
console.log("print Frame");
}
}
class Picture extends Control {
print() {
console.log("print Picture");
}
}
class Button extends Control {
print() {
console.log("print Button");
}
}
class Label extends Control {
print() {
console.log("print Label");
}
}
class CheckBox extends Control {
print() {
console.log("print CheckBox");
}
}
class TextBox extends Control {
print() {
console.log("print TextBox");
}
}
class LinkLabel extends Control {
print() {
console.log("print LinkLabel");
}
}
class PasswordBox extends Control {
print() {
console.log("print PasswordBox");
}
}
function main() {
let w = new Form();
w.add(new Picture());
w.add(new Button());
w.add(new Button());
let f = new Frame();
f.add(new Label());
f.add(new CheckBox());
f.add(new TextBox());
f.add(new Label());
f.add(new LinkLabel());
f.add(new Label());
f.add(new PasswordBox());
w.add(f);
w.print();
}
main();

运行结果如下图所示:

作业二

学习总结:

  • 组合模式为处理树形结构提供解决方案,它描述了如何将容器和叶子进行递归组合,使得用户在使用时无需区分,可以一致的对待容器和叶子

用户头像

大大猫

关注

还未添加个人签名 2019.04.06 加入

还未添加个人简介

评论

发布
暂无评论
第三周课后练习