C# 设计模式(11)外观模式

外观模式

1. 分层、封装 减少上层复杂度

代码实现:

商品下单走物流:

namespace FacadePattern.User
{
    public interface IUser
    {
        public bool CheckUser(int userId);
    }
    public class User:IUser
    {
        public int Id { get; set; }
        public bool CheckUser(int userId)
        {
            bool ret = userId > 0;

            return ret;
        }
    }
}
namespace FacadePattern.Order
{
    public interface IOrder
    {
        public bool CheckOrder(int userId, int orderId);
        public void CreatOrder(int userId,int orderId);
    }
    public class Order:IOrder
    {
        public int Id { get; set; }

        public bool CheckOrder(int userId, int orderId)
        {
            bool ret = (orderId > 0 && userId > 0);
            return ret;
        }

        public void CreatOrder(int userId, int orderId)
        {
            Console.WriteLine($"UserId{userId} create OrderId{orderId} Order");
        }
    }
}
namespace FacadePattern.Logistic
{
    public interface ILogistic
    {
        bool CheckLogistic(int logisticId, int orderId);

        void CreateLogistic(int logisticId, int orderId);
    }
    public class Logistic : ILogistic
    {
        public int Id { get; set; }
        public bool CheckLogistic(int logisticId,int orderId)
        {
            bool ret = logisticId > 0 && orderId>0;
            return ret;
        }

        public void CreateLogistic(int logisticId, int orderId)
        {
            Console.WriteLine($"OrderId{orderId} Generate LogisticId{logisticId} logistic");
        }
    }
}

外观封装:

    public class FacadeEncapsulation
    {
        public void GenerateOrder(int userId, int orderId, int logisticId)
        {
            IUser user = new User.User();
            IOrder order = new Order.Order();
            ILogistic logistic = new Logistic.Logistic();

            if (!user.CheckUser(userId))
            {
                Console.WriteLine("user is wrong!");
            }
            else if (!order.CheckOrder(userId, orderId))
            {
                Console.WriteLine("order is wrong!");
            }
            else if (!logistic.CheckLogistic(logisticId, orderId))
            {
                Console.WriteLine("logistic is wrong!");
            }
            else
            {
                order.CreatOrder(userId, orderId);
                logistic.CreateLogistic(logisticId, orderId);
            }
        }
    }

代码调用:

    class Program
    {
        static void Main(string[] args)
        {
            FacadeEncapsulation facadeEncapsulation = new FacadeEncapsulation();
            facadeEncapsulation.GenerateOrder(01,02,03);
        }
    }

结果:

C# 设计模式(11)外观模式

 

上一篇:oracle 中decode的用法


下一篇:MySQL-数据库三范式