简体   繁体   中英

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. so I wish make Service class independent from User class.

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.

Then in the other SubProject, write UserSub : IUser that also implements the interface IUser.

That way Service is independent, but you'll still have to implement something in each project that uses Service. (Which you need to do anyway, because Service currently uses it as an inner variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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