简体   繁体   中英

Is ViewModel in MVVM using bridge or adapter design pattern?

I am studying about design patterns of GoF and analyzing a C# project. Is the ViewModel considered as Bridge or Adapter pattern? As it is the middle layer for Model and View?

Thanks.

Is the ViewModel considered as Bridge?

No, it is not. As wiki says:

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently". Yeah, it can be said that abstraction can be UI or XAML and implementation is a view model. From this point of view, yeah it has similarities. However, UI or XAML is not abstract class or interface. So it can be concluded that ViewModel is not Bridge pattern.

Is the ViewModel considered as Adapter?

No, it is not. The Adapter pattern is more about getting your existing code to work with a newer system or interface.

For example, you have existing code of Cat and Tiger :

public interface ICat
{
    void Sound();
}

public class Cat : ICat
{
    public void Sound()
    {
        Console.WriteLine("I am cat");
    }
}

and:

public interface ITiger
{
    void Sound();
}

public class Tiger : ITiger
{
    public void Sound()
    {
        Console.WriteLine("I am Tiger");
    }
}

And then it is necessary to use Tiger instead of Cat . But how we can do it? We can use Adapter pattern:

public class TigerAdapter : ICat
{
    ITiger _tiger;

    public TigerAdapter(ITiger tiger)
    {
        _tiger = tiger; 
    }

    public void Sound()
    {
        _tiger.Sound();
    }
}

And then it can be used like this:

List<ICat> cats = new List<ICat>()
{
    new TigerAdapter(new Tiger())
};

But if you have existing view model that cannot be used in another View, then you can create class that adapts existing View Model for existing View Model. Then it can be said that you used Adapter pattern.

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