我希望能夠定義一些對象並將一些「行爲」附加到該對象中的行爲不在對象中的行爲。 Rails就像:acts_as_taggable。作爲一個具體的例子,我想說任務可以被標記。我不想在任務中編寫任何有關通過...接口「啓用」行爲的代碼的任何內容嗎?這是我的問題。你不能把實現放在一個接口中。我不想污染我的BaseObject [抽象?]類與所有的可能的實現。c# - 如何使用接口和/或抽象類正確地執行MULTIPLE「mixins」
對象:任務,注意
行爲:可加標籤,通過電子郵件發送,可印刷,可延遲(
任務可被標記,通過電子郵件發送,打印和推遲 的註記可被標記,通過電子郵件發送,打印,而不是推遲。
baseobject
public class BaseObject
{
Guid ID { get; set; }
}
個tag.cs
public class Tag : BaseObject
{
public Guid Id { get; set; }
public String Title { get; set; }
}
itaggable.cs
public interface ITaggable
{
void AddTag(Tag tag);
... other Tag methods ...
}
task.cs
public class Task : BaseObject, ITaggable, IEmailable, IPrintable
{
Task specified functionality... nothing about "taggging"
}
note.cs
...
TagCollection.cs
public class TagCollection : List<Tag>
{
public string[] ToStringArray()
{
string[] s = new string[this.Count];
for (int i = 0; i < this.Count; i++)
s[i] = this[i].TagName;
return s;
}
public override string ToString()
{
return String.Join(",", this.ToStringArray());
}
public void Add(string tagName)
{
this.Add(new Tag(tagName));
}
ITaggable的實現看起來像
{
private TagCollection _tc;
private TagCollection tc
{
get
{
if (null == _tc)
{
_tc = new TagCollection();
}
return _tc;
}
set { _tc = value; }
}
public void AddTag(Tag tag)
{
tc.Add(tag);
}
public void AddTags(TagCollection tags)
{
tc.AddRange(tags);
}
public TagCollection GetTags()
{
return tc;
}
}
那麼什麼是做到這一點的正確/最佳方法是什麼?
傑森
有趣的是,我將不得不多想一想這個。 – user166255 2010-01-13 19:33:01