asp.net 组合模式的一个例子_php实例
程序员文章站
2022-04-06 09:02:26
...
复制代码 代码如下:
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
///
/// 否操作
///
ISpecification
}
///
/// 基类
///
public abstract class CompositeSpecification
{
public abstract bool IsSatisfiedBy(T candidate);
public ISpecification
{
return new AndSpecification
}
public ISpecification
{
return new NotSpecification
}
}
///
/// 与操作
///
public class AndSpecification
{
private ISpecification
private ISpecification
public AndSpecification(ISpecification
{
this.leftSpecification = leftSpecification;
this.rightSpecification = rightSpecification;
}
public override bool IsSatisfiedBy(T entity)
{
return leftSpecification.IsSatisfiedBy(entity) && rightSpecification.IsSatisfiedBy(entity);
}
}
///
///否操作
///
public class NotSpecification
{
private ISpecification
public NotSpecification(ISpecification
{
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
private ISpecification
private ISpecification
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
return canRent.IsSatisfiedBy(this);
}
}
}