如果沒有上下文,這很難回答,所以我會嘗試圍繞我的信息製作一些東西,希望它能給你一個想法。
創建像這樣
interface ISpecification<T>
{
IsSatisfiedBy(T obj);
}
一個簡單的規範接口,假裝你有 '銀行' 看起來像
interface IBank
{
LedgerCode LedgerCode { get; set; }
}
基本接口和LedgerCodes
[Flags]
enum LedgerCodes
{
SUBS, BO, RCC
}
您的枚舉可以做一個簡單的分類賬代碼規範來檢查一個IBank的LedgerCodes(這是相當普遍的,你需要讓您的具體需要)
class LedgerCodeSpec : ISpecification<IBank>
{
private LedgerCode code;
public LedgerCodeSpecification(LedgerCode code)
{
this.code = code
}
public override bool IsSatisfiedBy(IBank obj)
{
return obj.LedgerCode == code;
}
}
在適當的地方,你可以用你的規範,在這裏我用它來提供簡單的驗證。另一個用途是用於「選擇」,例如從存儲庫
最後一些代碼來快速測試得到的數據/證明上述
class Main
{
public static void Main()
{
var spec = new LedgerCodeSpec(LedgerCodes.SUB)
var blueBank = new Bank(spec);
Console.WriteLine(blueBank.IsValid); // false
blueBank.LedgerCode = LedgerCodes.RCC | LedgerCodes.SUB;
Console.WriteLine(blueBank.IsValid); // false
blueBank.LedgerCode = LedgerCodes.SUB;
Console.WriteLine(blueBank.IsValid); // true
}
}
有在網絡上的一些很好的例子將擴展方法,也覆蓋運營商提供一個簡潔,更自然的可讀規格例如
class MessageSpecification : Specification<string>
{
public const int MIN_LENGTH = 5;
public const int MAX_LENGTH = 60;
public override bool IsSatisfiedBy(string s)
{
Specification<string> length = new LengthSpecification(MIN_LENGTH, MAX_LENGTH);
Specification<string> isNull = new IsNullSpecification<string>();
Specification<string> spec = length && !isNull;
return spec.IsSatisfiedBy(s);
}
}
我目前使用的模式的方式可能是矯枉過正,但我喜歡去除,再利用,一般使邏輯更OO的思想。
編輯:閱讀了一些評論後,你的問題似乎更多地涉及到一般的調度問題,而不是規範模式。給你的接口,你可以更簡單地做。
class BankFacade
{
public Send(IBlueBank bank)
{
// validate with specification
// do stuff with IBlueBank
}
public Send(IRedBank bank)
{
// validate with specification
// do stuff with IRedBank
}
//...
}
想着一些可以,但是你可能並不真正需要的模式,你可以做沿着
class Parser
{
static class RedBankSpecification : ISpecification<XElement>
{
public override bool IsSatisfiedBy(XElement element)
{
return element.Value.equals("RED");
}
}
public void Parse(XDocument doc)
{
var rspec = new RedBankSpecification();
foreach(XElement e in doc)
{
if (r.IsSatisfiedBy(e))
{
IRedBank bank = new RedBank(e);
bankFacade.Send(bank);
}
}
//...
}
}
線的東西,你shuoldn't試圖鞋拔子問題到它
你英語不錯,你只需要學習如何更好地提出問題。有[維基百科](http://en.wikipedia.org/wiki/Specification_pattern)上的示例代碼,如果你能解釋你對此不瞭解的內容,也許會更好(不是100%肯定)? – Ben
我的確讀過維基百科,但它太多了,難以理解。我更喜歡符合我的要求的示例代碼。如果你不介意給我示例代碼:) – user1358072
這是一個很好的代碼示例(不是你的具體域名,但很說明):http://www.dimecasts.net/Content/WatchEpisode/139 –