POO和接口(在C#中) [英] POO and Interface (in C#)

查看:169
本文介绍了POO和接口(在C#中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要了解界面:

我有这样的结构:

Core (contain Interface)
BLL (Contain object who implement interface 
DAL (Contain Data access)
IHM (Call BLL object)

例如,我有一个Interface Core.IVehicle,它描述了像这样的基本车辆:

For example, i have an Interface Core.IVehicle who describe a basic vehicle like :

Color
Speed

还有一个方法:

LoadVehicle(int id) //return a iVehicule with speed and color

在我的BLL中,我有一个实现"Core.IVehicle"的对象"BLL.Car". 因此,我将有一个LoadVehicle方法并访问DAL以获取基本信息

In my BLL, I have an object "BLL.Car" who implement "Core.IVehicle". So, i will have a LoadVehicle method and access to DALfor get basics informations

但是DAL需要返回实现的对象"BLL.Car".但是由于循环依赖,我无法引用BLL.

But DAL need to return an object "BLL.Car" implemented. But i can't make a reference to BLL because of Circular Dependencies.

我想念什么?我的DAL如何返回实现的对象"BLL.Car"?

What i've miss? How my DAL can return an object "BLL.Car" implemented?

推荐答案

但是DAL需要返回实现的对象"BLL.Car".

But DAL need to return an object "BLL.Car" implemented.

这可能就是混乱所在.

This is probably where the confusion lies.

您的DAL 不应返回BLL版本的Car,DAL应该具有其自己的Car版本,又名 entity / DAO (数据访问对象). BLL应该在DAL中查询汽车的实体"(无论是作为DTO还是IVehicle返回),并构造它自己的Car aka领域模型表示.

Your DAL should not return the BLL version of Car, the DAL should have it's own version of Car aka entity / DAO (data access object). The BLL should query the DAL for the car "entity" (whether it be returned as a DTO or an IVehicle) and construct it's own representation of Car aka Domain Model.

因此,总而言之,您应该具有Car的2个(或3个,如果您还需要视图模型)版本,即

So to summarise you should have 2 (or 3 if you want a view model as well) versions of Car i.e.

实体/DAO(DAL)

public class Car : IVehicle
{
}
...
public class CarRepository
{
    ...
    public IVehicle LoadVehicle(int id)
    {
        var entity = // query DB for instance of DAL.Car
        return entity;
    }
}

域模型(BLL)

public class Car : IVehicle
{
}
...
public class CarService
{
    public IVehicle FindCarById(int id)
    {
        var repo = new DAL.CarRepository(...);
        var carEntity = repo.LoadVehicle(id); // returns DAL.Car instance 
        return new BLL.Car // we turn DAL.Car into our DLL.Car
        {
            Color = carEntity.Color,
            Speed = carEntity.Speed
        };
    }
}

IHM(查看)

public class Controller
{
    public void ViewCarDetails(int id)
    {
        var carService = new BLL.CarService();
        var car = carService.FindCarById(id);
        // populate UI with `car` properties
    }
}

由于IVehicle在核心DLL中,因此可以在所有层之间共享,因此您不必担心循环引用,并且它为您提供了一致的返回类型.

Because IVehicle is in the Core DLL it can be shared across all your layers, so you don't need to worry about circular references, and it gives you a consistent return type.

这篇关于POO和接口(在C#中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆