03周作业——设计模式
保证系统中只产生Singleton的单一实例。实现方式分为和,需要考虑线程安全,可以使用语言的特性来实现。
以下以来完成,实在是非常简单,构造函数私有化,类的属性自动实现


C#版的设计和实现如下:

Component 抽象类
namespace arch.Composite
{
using System;
public abstract class Component
{
protected string name;
public Component(string name)
{
this.name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public virtual void Print()
{
Console.WriteLine("print {0}", this.name);
}
}
}
Container 类: 可以拆分成较多的容器类组建,比如Window, Frame, Panel 等,不一一写,统称Container
namespace arch.Composite
{
using System;
using System.Collections.Generic;
///
/// Container Component: it can be Window, Frame, Panel ...
///
public class Container : Component
{
private IList children = new List();
public Container(string name) : base(name)
{ }
public override void Add(Component c)
{
this.children.Add(c);
}
public override void Print()
{
Console.WriteLine("print {0}", this.name);
foreach (var item in this.children)
{
item.Print();
}
}
public override void Remove(Component c)
{
this.children.Remove(c);
}
}
}
FormComponent 类:可以拆分成很多的单一组件,比如Button, Label, TextBox, CheckBox 等,不一一写,统称 FormComponent
namespace arch.Composite
{
///
/// Form Component: it can be Button, Label, TextBox, CheckBox ...
///
public class FormComponent : Component
{
public FormComponent(string name) : base(name)
{ }
public override void Add(Component c)
{
throw new System.NotImplementedException();
}
public override void Remove(Component c)
{
throw new System.NotImplementedException();
}
}
}
输出结果
