架构师训练营 第三周 作业
发布于: 2020 年 06 月 23 日
作业一:
1. 请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。

- 请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。 
主要接口是printable,需要实现print 方法。
所有的组件包括容器,都继承自component,它实现print 方法。
容器多包含了一个list用来装components。
go 实现,代码如下
package mainimport (	"container/list"	"fmt")type printable interface {	Print()}type component struct {	name          string	componentType string}func (p *component) Print() {	fmt.Println(fmt.Sprintf("print %s(%s)", p.componentType, p.name))}// Container control can hold other controlstype container struct {	component	components list.List}func (c *container) Print() {	c.component.Print()	for i := c.components.Front(); i != nil; i = i.Next() {		i.Value.(printable).Print()	}}func (c *container) AddComponent(cpnt printable) {	c.components.PushBack(cpnt)}type winform struct {	container}type picture struct {	component}type button struct {	component}type frame struct {	container}type label struct {	component}type textBox struct {	component}type passwordBox struct {	component}type checkBox struct {	component}type linkLabel struct {	component}func newWinform(name string) *winform {	return &winform{container{component: component{componentType: "WinForm", name: name}}}}func newPicture(name string) *picture {	return &picture{component{componentType: "Picture", name: name}}}func newButton(name string) *button {	return &button{component{componentType: "Button", name: name}}}func newFrame(name string) *frame {	return &frame{container{component: component{componentType: "Frame", name: name}}}}func newLabel(name string) *label {	return &label{component{componentType: "Label", name: name}}}func newTextBox(name string) *textBox {	return &textBox{component{componentType: "TextBox", name: name}}}func newPasswordBox(name string) *passwordBox {	return &passwordBox{component{componentType: "PasswordBox", name: name}}}func newCheckBox(name string) *checkBox {	return &checkBox{component{componentType: "CheckBox", name: name}}}func newLinkLabel(name string) *linkLabel {	return &linkLabel{component{componentType: "LinkLabel", name: name}}}func main() {	form := newWinform("MainForm")	form.AddComponent(newPicture("LOGO"))	form.AddComponent(newButton("sign in"))	form.AddComponent(newButton("sign up"))	frame := newFrame("Frame1")	form.AddComponent(frame)	frame.AddComponent(newLabel("user name"))	frame.AddComponent(newTextBox("user name textbox"))	frame.AddComponent(newLabel("password"))	frame.AddComponent(newPasswordBox("password box"))	frame.AddComponent(newCheckBox("keep sign in"))	frame.AddComponent(newLabel("keep sign in"))	frame.AddComponent(newLinkLabel("forget password"))	form.Print()}
划线
评论
复制
发布于: 2020 年 06 月 23 日阅读数: 60
版权声明: 本文为 InfoQ 作者【一雄】的原创文章。
原文链接:【http://xie.infoq.cn/article/5c934ee0e0133d59ba0826b03】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。

一雄
关注
还未添加个人签名 2020.03.05 加入
还未添加个人简介











 
    
评论