简体   繁体   English

C#松耦合

[英]C# Loose coupling

I can't explain my problem in English. 我无法用英语解释我的问题。 so let me show my situation. 所以让我展示一下我的情况。

// in Main Project
public class User
{
    public int version
    {
        get;
        set;
    }
}


// in Common Project
public class Service : BaseService
{
    User _user;
    public void SetVersion(int versionID)
    {
        _user.version = versionID;
    }

    public bool HasMessage()
    {
        return GetMessage(user.version);
    }
}

And now I have another sub project. 现在我有另一个子项目。 and I need use Service class in there. 我需要在那里使用Service类。 so I wish make Service class independent from User class. 所以我希望使Service类独立于User类。

how do I do that? 我怎么做?

I have only below solution. 我只有下面的解决方案。 Is there any brilliant way? 有什么好办法吗?

public class Service : BaseService
{
    Action<int> _getCallBack;
    Func<int> _setCallBack;

    public Service(Action<int> getCallback, Func<int> setCallBack)
    {
        _getCallback = getCallback;
        _setCallback = setCallback;
    }

    public void SetVersion(int versionID)
    {
        setCallback(versionID);
    }

    public bool HasMessage()
    {
         return GetMessage(getCallback())
    }
}

It depends on your use of 'User' in service. 这取决于您在服务中对“用户”的使用。 You can add an interface IUser in Common project, and have User implement it. 您可以在Common项目中添加接口IUser,并让User实施它。

Then in the other SubProject, write UserSub : IUser that also implements the interface IUser. 然后在另一个SubProject中,编写UserSub:IUser,它也实现了接口IUser。

That way Service is independent, but you'll still have to implement something in each project that uses Service. 这样,Service是独立的,但是您仍然必须在每个使用Service的项目中实现一些功能。 (Which you need to do anyway, because Service currently uses it as an inner variable. (无论如何,您都需要这样做,因为Service当前将其用作内部变量。

Yes there are several best practices which allow decoupling components, they are called design patterns. 是的,有几种允许对组件去耦的最佳实践,它们被称为设计模式。 I would recommend to take a look at all of them to decide which one fits your context best. 我建议看一下所有这些,以决定最适合您的情况。 All of them have advantages and disadvantages, application scope and impact. 它们都有优点和缺点,应用范围和影响。 There is no one brilliant solution for decoupling. 没有一种出色的解耦解决方案。

I think the command pattern can be the right one for your problem. 我认为命令模式可以解决您的问题。

See: http://www.dofactory.com/net/design-patterns and https://csharpdesignpatterns.codeplex.com 请参阅: http : //www.dofactory.com/net/design-patternshttps://csharpdesignpatterns.codeplex.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM