Learning Factory Design Patterns

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

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

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

However, the well-known advantage of the interface is its free connection, so why not use this template? If not, then why do all microsoft tools use interfaces, then?

I am surprised at the lack of answers. It seems that people know how to do something, but not quite like that.

+4
source share
2 answers

If you think about it, the abstract base class is like a partial implementation interface. Therefore, use an abstract base class if you have standard functions that will be used by all classes that the factory will create. If you do not have any implementation, just use the interface.

+1
source

You think about it wrong. Regardless of whether you use an interface or an abstract class, you must decide when creating the object. Later, when you decide to build it, you will use the abstract factory template.

They simply showed that they can handle any form of abstraction. An interface is generally considered "better" because it allows for a weaker link without forcing the constructor to not use your inheritance link. However, it’s even less likely to use factory to return an interface, because you usually want to give people the opportunity to implement their own implementation of interfaces, which is traditionally not a model of the factory template (although this certainly can be)

There is one specific advantage of using interfaces that I can think of; you can implement two different interfaces with the same class. Here is an example (pretty dumb):

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; } } 
+1
source

Source: https://habr.com/ru/post/1306852/


All Articles