架构师训练营 Week03
请在草稿纸上手写一个单例模式的实现代码,拍照提交作业
![](https://static001.geekbang.org/infoq/ba/ba943dd98acfa5895d21e93d86e8c8ad.png)
请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3
![](https://static001.geekbang.org/infoq/15/153b0c3d081d40358e2ab33551d7c919.png)
基类的定义
public class BaseFrame
{
protected string Content;
protected IList<BaseFrame> FramesList;
public BaseFrame(string content)
{
Content = content;
this.FramesList = new List<BaseFrame>();
}
public virtual void Add(BaseFrame _baseFrame)
{
if(_baseFrame == null)
{
return;
}
if(_baseFrame.FramesList.Count() > 0)
{
foreach(var item in _baseFrame.FramesList)
{
this.FramesList.Add(item);
}
}
else
{
this.FramesList.Add(_baseFrame);
}
}
public virtual void Delete(BaseFrame _baseFrame)
{
if (_baseFrame == null)
{
return;
}
if (this.FramesList.Count() > 0)
{
foreach (var item in _baseFrame.FramesList)
{
this.FramesList.Remove(item);
}
}
else
{
this.FramesList.Remove(_baseFrame);
}
}
public virtual void Print()
{
if(this.FramesList.Count > 0)
{
foreach(var item in this.FramesList)
{
Console.WriteLine(item.Content);
}
}
else
{
Console.WriteLine(this.Content);
}
}
}
子类的定义
public class WinFormWnd : BaseFrame
{
public WinFormWnd(string content) : base(content) { }
}
public class Picture : BaseFrame
{
public Picture(string content) : base(content) { }
}
public class Button : BaseFrame
{
public Button(string content) : base(content) { }
}
public class Frame : BaseFrame
{
public Frame(string content) : base(content) { }
}
public class Label : BaseFrame
{
public Label(string content) : base(content) { }
}
public class TextBox : BaseFrame
{
public TextBox(string content) : base(content) { }
}
public class PasswordBox : BaseFrame
{
public PasswordBox(string content) : base(content) { }
}
public class CheckBox : BaseFrame
{
public CheckBox(string content) : base(content) { }
}
public class LinkLabel : BaseFrame
{
public LinkLabel(string content) : base(content) { }
}
主函数入口:
static void Main(string[] args)
{
BaseFrame wnd = new WinFormWnd("Window窗口");
wnd.Add(new Picture("LOGO图片"));
wnd.Add(new Button("登录"));
wnd.Add(new Button("注册"));
var frame1 = new Frame("Frame1");
frame1.Add(new Label("用户名"));
frame1.Add(new Label("密码"));
frame1.Add(new PasswordBox("密码框"));
frame1.Add(new Label("记住"));
frame1.Add(new CheckBox("复选框"));
frame1.Add(new TextBox("文本框"));
frame1.Add(new LinkLabel("忘记密码"));
wnd.Add(frame1);
Console.WriteLine("****Print Wnd********");
wnd.Print();
Console.WriteLine("****Print Frame1********");
frame1.Print();
Console.ReadKey();
}
评论