开发者

Exploring the Factory Design Pattern

开发者 https://www.devze.com 2022-12-26 13:35 出处:网络
There was an article here: http://msdn.microsoft.com/en-us/library/Ee817667%28pandp.10%29.aspx The first part of tut implemented this pattern with abstract classes. The second part shows an example w

There was an article here: http://msdn.microsoft.com/en-us/library/Ee817667%28pandp.10%29.aspx

The first part of tut implemented this pattern with abstract classes. The second part shows an example with Interface class. But nothing in this article discusses why this pattern would rather use abstract or interface.

So what explanation (advantages of one over the other) would you give ? Not in general but for this precise pattern.

Nevertheless the well known benefit of Interface is loose coupling so why wouldn't it apply to this pattern ? If not Why all microsoft stuffs use In开发者_如何学Goterfaces then ?

I'm suprised by the lack of answers. It seems people know how to do things but not really why.


If you think about it, an abstract base class is like an interface with a partial implementation. Therefore, use an abstract base class if you have some standard functionality that will be shared by all classes that will be created by the factory. If you don't have any implementation, just use an interface.


You're thinking about it wrong. Whether you use an interface or an abstract class should be a decision you make when creating the entity. Later on, when you're deciding to construct it you would use an abstract factory pattern.

They were just merely showing that it can handle either form of abstraction. An interface is generally viewed as "better" since it allows looser coupling by not forcing a constructor and not using up your inheritance link. However, it is also rarer to use a factory to return an interface, since usually you want to give people the ability to inject their own implementation of interfaces, which is not traditionally a role of the factory pattern (though it certainly can be)

There is one specific benefit to using interfaces that I can think of; you can implement two different interfaces with the same class. Here is a (fairly stupid) example:

interface IProvideInfo {
  string Get();
}
interface IProvideConnectionString : IProvideInfo { }
interface IProvideCurrentUserName : IProvideInfo { }

class CurrentContextProvider : IProvideConnectionString, IProvideCurrentUserName  {
  string IProvideConnectionString.Get() {
    return ConfigurationManager.ConnectionStrings["db"];
  }
  string IProvideCurrentUserName.Get() {
    return _currentUserName;
  }
  string _currentUserName;
  public string SetCurrentUserName(string s) {
    _currerntUserName = s;
  }
}

public class InfoProviderFactory {
  CurrentContextProvider _provider = new CurrentContextProvider()
  public IProvideInfo GetProvider(string key) {
    return _provider;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号