Layered Supertype

Layered Supertype(层超类型)模式定义了一个对象,改对象充当自己所在层的所有类型的基类,而且采用类继承机制实现。

意图:当某层中所有对象共享一组公共的业务逻辑时,可以使用Layered Supertype模式来移除重复的逻辑并将逻辑集中起来。

using System;
using System.Collections.Generic;
using System.Linq;

namespace Chap5.LayerSuperType.Model
{
    /// <summary>
    /// 1、抽象类EntityBase是所有业务实体都要继承的Supertype(超类型),所有实体都需要一个标识符,所有该Supertype类可以提供保存ID,并确保一经设置绝不改变的逻辑。
    /// 2、该Supertype类提供一个简单的框架来检查实体对象是否合法。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class EntityBase<T>
    {
        private T _id;
        private IList<string> _brokenRules = new List<string>();
        private bool _idHasBeenSet = false;
        public EntityBase()
        {

        }
        public EntityBase(T id)
        {
            this.ID = id;
        }


        public T ID
        {
            get;
            set
            {
                if (_idHasBeenSet)
                    ThrowExceptionIfOverwritingAnd();
                _id = value;
                _idHasBeenSet = true;
            }
        }

        private void ThrowExceptionIfOverwritingAnd()
        {
            throw new ApplicationException("You cannot change the id of an entity.");
        }
        public bool IsValid()
        {
            ClearCollectionOfBrokenRules();
            CheckForBrokenRules();
            return _brokenRules.Count() == 0;
        }

        private void ClearCollectionOfBrokenRules()
        {
            _brokenRules.Clear();
        }
        protected abstract void CheckForBrokenRules();

        public IEnumerable<string> GetBrokenBusinessRules()
        {
            return _brokenRules;
        }
        protected void AddBrokenRule(string brokenRule)
        {
            _brokenRules.Add(brokenRule);
        }
    }
}
EntityBase.cs

 

namespace Chap5.LayerSuperType.Model
{
    public class Customer : EntityBase<long>
    {
        public Customer()
        {

        }
        public Customer(long id)
            : base(id)
        {

        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        protected override void CheckForBrokenRules()
        {
            if (string.IsNullOrEmpty(FirstName))
                base.AddBrokenRule("You must supply a first Name");

            if (string.IsNullOrEmpty(LastName))
                base.AddBrokenRule("You must supply a last Name");
        }
    }
}
Customer.cs

 

Layered Supertype模式不属于GOF的设计模式。

posted @ 2020-06-07 21:53  水墨晨诗  阅读(175)  评论(0编辑  收藏  举报