asp.Netコンビネーションモードの一例

4656 ワード

 
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer
{
IsActive = true,
LateFees = 100M,
TotalRentNumber = 10
};
Console.WriteLine(customer.CanRent());
Console.ReadKey();
}
}
public interface ISpecification
{
///
///
///

bool IsSatisfiedBy(T entity);
///
///
///

ISpecification And(ISpecification other);
///
///
///

ISpecification Not();
}
///
///
///

public abstract class CompositeSpecification : ISpecification
{
public abstract bool IsSatisfiedBy(T candidate);
public ISpecification And(ISpecification other)
{
return new AndSpecification(this, other);
}
public ISpecification Not()
{
return new NotSpecification(this);
}
}
///
///
///

public class AndSpecification : CompositeSpecification
{
private ISpecification leftSpecification;
private ISpecification rightSpecification;
public AndSpecification(ISpecification leftSpecification, ISpecification rightSpecification)
{
this.leftSpecification = leftSpecification;
this.rightSpecification = rightSpecification;
}
public override bool IsSatisfiedBy(T entity)
{
return leftSpecification.IsSatisfiedBy(entity) && rightSpecification.IsSatisfiedBy(entity);
}
}
///
///
///

public class NotSpecification : CompositeSpecification
{
private ISpecification innerSpecification;
public NotSpecification(ISpecification innerSpecification)
{
this.innerSpecification = innerSpecification;
}
public override bool IsSatisfiedBy(T entity)
{
return !innerSpecification.IsSatisfiedBy(entity);
}
}
///
///
///

public class HasReachedMaxSpecification : CompositeSpecification
{
public override bool IsSatisfiedBy(Customer entity)
{
return entity.TotalRentNumber > 5;
}
}
///
///
///

public class CustomerActiveSpecification : CompositeSpecification
{
public override bool IsSatisfiedBy(Customer entity)
{
return entity.IsActive;
}
}
///
///
///

public class CustomerHasLateFeesSpecification : CompositeSpecification
{
public override bool IsSatisfiedBy(Customer entity)
{
return entity.LateFees > 0;
}
}
public class Customer
{
private ISpecification hasReachedRentalThreshold;
private ISpecification customerIsActive;
private ISpecification customerHasLateFees;
public Customer()
{
hasReachedRentalThreshold = new HasReachedMaxSpecification();
customerIsActive = new CustomerActiveSpecification();
customerHasLateFees = new CustomerHasLateFeesSpecification();
}
///
/// DVD
///

public int TotalRentNumber
{
get;
set;
}
///
///
///

public bool IsActive
{
get;
set;
}
///
///
///

public decimal LateFees
{
get;
set;
}
public bool CanRent()
{
ISpecification canRent = customerIsActive.And(hasReachedRentalThreshold.Not()).And(customerHasLateFees.Not());
return canRent.IsSatisfiedBy(this);
}
}
}