Does ChannelFactory implement a factory pattern? - wcf

I’ve started learning WCF and I’m already utterly confused. I did a bit of reading on factory pattern and I can’t figure out how or why does ChannelFactory<> implement it.
Namely, the whole idea of a factory pattern is that factory abstracts the creation and initialization of the product from the client and thus if new type of product is introduced, client code doesn’t need to change and thus can immediately start using the new product.
ChannelFactory<IRequestChannel> factory = new
ChannelFactory<IRequestChannel>(binding, address);
IRequestChannel channel = factory.CreateChannel();
The following is not a valid code, but it’s just used to demonstrate that, as far as I can tell, ChannelFactory doesn’t bring any benefits over directly instantiating specific channel class:
IRequestChannel channel=new RequestChannelClass(binding, address);
a) Only benefit of the first example ( implementing the factory pattern ) is that client code doesn’t need to change in the event that the type of object returned by factory.CreateChannel is changed sometime in the future.
But if that’s the reason for implementing factory pattern, then any method returning an object should implement a factory pattern, just in case the type of returned object ever changes in the future?!
c) Thus, if ChannelFactory<>.CreateChannel really implemented factory pattern, then client code would be able to inform factory.GetFactory (say via parameter) of what type should an object/product returned by factory.CreateFactory be?!
d) Similarly, as far as I can tell, ChannelFactory class also doesn't implement a factory pattern?
thank you
REPLYING TO Justin Niessner:
b) The Factory pattern doesn't
necessarily require you to be able to
specify the concrete type to be
created. It also allows for the
factory to determine the concrete type
based on the parameters passed to it
(in this case, binding and address).
So ChannelFactory.CreateChannel choose a concrete type to return based on binding and address values? I thought it always returns the same concrete type, regardless of address and binding values?!
As I’ve asked the other two posters, would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Kevin Nelson
A) There are 2 benefits. 1)
implementing code doesn't have to
change if you start using a new
implementation of IRequestChannel.
True, but as I’ve mentioned to other posters, if that’s the only requirement for class to be qualified as a class implementing a factory pattern , then any class with a method ( with an interface type as return type ) that creates and returns a concrete instance, implements a factory pattern? As far as I can tell, factory pattern is when factory produces different products based on values somehow supplied by a client code?!
On the other hand, if I correctly understood Steve Ellinger, then based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will choose the concrete type to return based on binding and address values( supplied to constructor ). If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Steve Ellinger
IRequestChannel is implemented by the
abstract class RequestChannel. In .Net
4.0 HttpChannelFactory.HttpRequestChannel,
ReliableRequestSessionChannel and
StreamedFramingRequestChannel all
inherit from RequestChannel. So:
a) You say the only benefit, but
actually I think this is a significant
benefit. Keep in mind, this also makes
WCF extensible and more flexible.
But then we could claim that any class with a method ( with an interface type as return type ) that creates and returns a concrete instance implements a factory pattern?
c) The client code does tell the
factory which to return, indirectly by
the passed binding and address.
I thought ChannelFactory.CreateChannel will always return in instance of the same concrete type, regardless of the binding and address passed to constructor of ChannelFactory.But you’re saying that based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will return one of the following types: HttpChannelFactory.HttpRequestChannel ,ReliableRequestSessionChannel and StreamedFramingRequestChannel?
If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
SECOND REPLY TO Steve Ellinger
a) So depending on the binding and address values, ChannelFactory.CreateChannel returns either HttpRequestChannel ,ReliableRequestSessionChannel or StreamedFramingRequestChannel? Or may it also return some other types also?
b) if client code will always use channel instance of the same type (say HttpRequestChannel ), then there's nothing wrong if instead of using ChannelFactory.CreateChannel we directly instantiate HttpRequestChannel instance:
HttpRequestChannel channel = new HttpRequestChannel( ... )
c) BTW - any idea why msdn doesn't contain any entries describing HttpRequestChannel ,ReliableRequestSessionChannel and `StreamedFramingRequestChannel' classes?

IRequestChannel is implemented by the abstract class RequestChannel. In .Net 4.0 HttpChannelFactory.HttpRequestChannel, ReliableRequestSessionChannel and StreamedFramingRequestChannel all inherit from RequestChannel. So:
a) You say the only benefit, but actually I think this is a significant benefit. Keep in mind, this also makes WCF extensible and more flexible.
c) The client code does tell the factory which to return, indirectly by the passed binding and address. I for one would not want to go through all my code to change a concrete type because Microsoft decided to obsolete the one I was using.
d) Yes, given the structure mentioned at the start, this is a typical Factory pattern implementation.
Edit:
a factory pattern?
But then we could claim that any class
with a method ( with an interface type
as return type ) that creates and
returns a concrete instance implements
a factory pattern?
Not necessarily, to quote the Design Patterns book: the abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Yes
Edit2:
a) It can return other types because it is possible to create custom bindings in WCF
b) & c) HttpChannelFactory.HttpRequestChannel is a protected class, ReliableRequestSessionChannel and StreamedFramingRequestChannel are internal classes; this is why you can't find them on msdn, and also why you can't instantiate these classes directly. I found out about them via Reflector, my point in mentioning them is that ChannelFactory does not necessarily return the same concrete type all the time

The Factory pattern is used to return a Concrete Implementation of a more generic class/interface.
In this case, ChannelFactory is returning a concrete implementation of IRequestChannel. Nowhere in any of your code are you telling the factory which concrete class to return which is what makes this a Factory. As for your points:
a) It is often considered good coding practice to return the least specific type possible. If you can get away with returning an instance of an interface, do it. It will reduce maintenance headaches in the future.
Keep in mind though that returning the least specific type has nothing to do with the Factory pattern. The Factory pattern is specific to the creation of an instance of an object.
b) The Factory pattern doesn't necessarily require you to be able to specify the concrete type to be created. It also allows for the factory to determine the concrete type based on the parameters passed to it (in this case, binding and address).
c) Yes, the ChannelFactory does implement the Factory pattern.

There are others that are probably more efficient with patterns (and explaining them) than I am, but here goes:
A) There are 2 benefits. 1) implementing code doesn't have to change if you start using a new implementation of IRequestChannel. 2) This also enables you to make Mock objects. In your unit test project, you tell your ChannelFactory to instantiate a Mock IRequestChannel. This way, you can focus your unit test onto just the specifics of the method you are testing rather than having to create a behemoth test that instantiates real instances of everything, etc. (If you're unfamiliar, look up Test Driven Development (TDD), Inversion of Control (IoC), and Dependency Injection (basically a subset of IoC).
B) I would say that you generally want to use the factory pattern between layers, not within layers. E.g. your service layer would implement a factory for your repository layer classes. This way, if your ICustomerRepostory changes from an NHibernateCustomerRepository to a CouchDBCustomerRespository...your service layer doesn't have to know anything about this change.
Other poster answered the other issues, I think...so I'll leave C & D alone.
REPLY EDIT:
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Sorry, probably over my head as to the semantics of it...but to my understanding, the point isn't so much whether it does return more than one concrete class, but in its ability to return a different concrete class if the need arises. If it's not able to produce different concrete classes, then it wouldn't be a factory...but if it "can" produce different concrete classes if and when the need arises, then it is a factory pattern. Beyond that, I'll have to declare ignorance...and even in that, I'm not saying I can't be wrong.

Related

OO principle: c#: design to interface and not concrete classes

I have some questions about the affects of using concrete classes and interfaces.
Say some chunk of code (call it chunkCode) uses concrete class A. Would I have to re-compile chunkCode if:
I add some new public methods to A? If so, isn't that a bit stange? After all I still provide the interface chunkCode relies on. (Or do I have to re-compile because chunkCode may never know otherwise that this is true and I haven't omitted some API)
I add some new private methods to A?
I add a new public field to A?
I add a new private field to A?
Factory Design Pattern:
The main code doesn't care what the concrete type of the object is. It relies only on the API. But what would you do if there are few methods which are relevant to only one concrete type? This type implements the interface but adds some more public methods? Would you use some if (A is type1) statements (or the like) the main code?
Thanks for any clarification
1) Compiling is not an activity in OO. It is a detail of specific OO implementations. If you want an answer for a specific implementation (e.g. Java), then you need to clarify.
In general, some would say that adding to an interface is not considered a breaking change, wheras others say you cannot change an interface once it is published, and you have to create a new interface.
Edit: You specified C#, so check out this question regarding breaking changes in .Net. I don't want to do that answer a disservice, so I won't try to replicate it here.
2) People often hack their designs to do this, but it is a sign that you have a poor design.
Good alternatives:
Create a method in your interface that allows you to invoke the custom behavior, but not be required to know what that behavior is.
Create an additional interface (and a new factory) that supports the new methods. The new interface does not have to inherit the old interface, but it can if it makes sense (if an is-a relationship can be expressed between the interfaces).
If your language supports it, use the Abstract Factory pattern, and take advantage of Covariant Return Types in the concrete factory. If you need a specific derived type, accept a concrete factory instead of an abstract one.
Bad alternatives (anti-patterns):
Adding a method to the interface that does nothing in other derived classed.
Throwing an exception in a method that doesn't make sense for your derived class.
Adding query methods to the interface that tell the user if they can call a certain method.
Unless the method name is generic enough that the user wouldn't expect it to do anything (e.g. DoExtraProcessing), then adding a method that is no-op in most derived classes breaks the contract defined by that interface.
E.g.: Someone invoking bird.Fly() would expect it to actually do something. We know that chickens can't fly. So either a Chicken isn't a Bird, or Birds don't Fly.
Adding query methods is a poor work-around for this. E.g. Adding a boolean CanFly() method or property in your interface. So is throwing an exception. Neither of them get around the fact that the type simply isn't substitutable. Check out the Liskov Substitution Principle (LSP).
For your first question the answer is NO for all your points. If it would be that way then backward compatibility would not make any sense. You have to recompile chunkCode only if you brake the API, that is remove some functionality that chunkCode is using, changing calling conventions, modifying number of parameters, these sort of things == breaking changes.
For the second I usually, but only if I really have to, use dynamic_cast in those situations.
Note my answer is valid in the context of C++;I just saw the question is language agnostic(kind of tired at this hour; I'll remove the answer if it offenses anybody).
Question 1: Depends on what language you are talking about. Its always safer to recompile both languages though. Mostly because chuckCode does not know what actually exists inside A. Recompiling refreshes its memory. But it should work in Java without recompiling.
Question 2: No. The entire point of writing a Factory is to get rid of if(A is type1). These if statements are terrible from maintenance perspective.
Factory is designed to build objects of similar type. If you are having a situation where you are using this statement then that object is either not a similar type to rest of the classes. If you are sure it is of similar type and have similar interfaces. I would write an extra function in all the concrete base classes and implement it only on this one.
Ideally All these concrete classes should have a common abstract base class or a Interface to define what the API is. Nothing other than what is designed in this Interface should be expected to be called anywhere in the code unless you are writing functions that takes this specific class.

Windsor Typed Factory facility, passing arguments when using singleton lifestyle

I am using Castle Windsor.
I have two component types where the implementation can be selected at runtime on a GUI. To handle this, I am resolving them by name. To handle resolving them by name, I am using the Typed Factory Facility.
One of the component types depends on the other. To handle the dependency, I am passing the argument as a factory method/constructor parameter argument.
Here is a redacted and abridged version of this factory interface:
public interface IModelFactory
{
IMyDomainCommandFactory GetFooCommandFactory();
IMyDomainCommandFactory GetBarCommandFactory();
IMyDomainStrategy GetCreateSpecificSizeStrategy(int size, IMyDomainCommandFactory commandFactory);
IMyDomainStrategy GetCreateUntilFailureStrategy(IMyDomainCommandFactory commandFactory);
}
Note that I am using my own implementations for IMyDomainCommandFactory, rather than using the Typed Factory facility. Those factories have intentionally complex behavior, and the facility doesn't suit their needs.
The problem I am noticing is that if I register my strategy components with a singleton lifestyle, I always get back the same instance, even if I pass different arguments to the getter.
In my opinion, this goes against the Principal of Least Astonishment, but maybe other people have a different opinion :) Should this be considered a bug?
If not, is there a clean way to get the container or factory to create only one instance per argument combination?
Depending how you look at it, but certainly instance per combination of parameters can't be called a singleton so I say it would go against PoLA if Windsor did implement the behavior you'd expect.
If you want it, you need a custom, non-singleton lifestyle.

When to use the abstract factory pattern?

I'm trying to succinctly describe when to use a factory, for both myself and my team. I ran across the following related questions, which helped somewhat:
When to use factory patterns?
(useful pdf link is broken)
How do you create your Factories?
(more 'how' rather than 'when')
What is your threshold to use factory instead of a constructor to create an object?
(some general answers)
Factory Pattern. When to use factory methods?
(more about factory methods than factory classes)
When to use Factory method pattern?
(again more about factory methods)
Based on these links, and a bunch of other sources (listed at the bottom), I've come up with the following:
When to use the abstract factory pattern:
when you use an interface var or the 'new' operator
e.g. User user = new ConcreteUserImpl();
and the code you are writing should be testable / extensible at some point
Explanation:
interfaces by their very nature imply multiple implementations (good for unit testing)
interface vars imply OCP- and LSP-compliant code (support sub-classing)
use of the 'new' operator breaks OCP/DI, because highly-coupled classes are hard to test or change
"Do I create a factory for every object type? That seems excessive."
no, you can have one (or a few) factories that produce a lot of (usually related) object types
e.g. appFactory.createUser(); appFactory.createCatalog(); etc.
When NOT to use a factory:
the new object is very simple and unlikely to be sub-classed
e.g. List list = new ArrayList();
the new object is not interesting to test
has no dependencies
performs no relevant or long-running work
e.g. Logger log = new SimpleLogger();
References:
http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html
http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
http://en.wikipedia.org/wiki/Dependency_Injection
http://en.wikipedia.org/wiki/Open_Closed_Principle
http://en.wikipedia.org/wiki/Liskov_substitution_principle
My question is: is my summary accurate, and does it make sense? Is there anything I've overlooked?
Thanks in advance.
I'd also say don't use a factory when you have a particular implementation that you want. To continue the List example, I know that I want an ArrayList because I'm doing random access. I don't want to rely on a factory getting this right when I can do it myself.
Conversely, when I don't want to know about the concrete subclass then I can use a factory and let it worry about which object to actually instantiate.
I guess I'd suggest that you add a bullet to the "when to use the abstract factory pattern" that says "and you don't really care which concrete subclass you get", and the converse to "when not to use a factory".
EDIT: Be careful to avoid the general-purpose tool-building factory factory factory.
In general, use it when you want to be able to switch of implementation by external configuration.
JDBC and JAXP are excellent examples. For more examples, check this answer.
Abstract Factory pattern provides with a way to encapsulate concrete factories that share some commonality with each other, meaning they implement same interface/abstract class.
You need to use factory pattern whenever you want to control the initialization of your objects, instead of giving the control to the consumer.

Can I make Rhino Mocks GenerateStub or GenerateMock return a new type every time?

I want to create an IList of objects that are all different concrete types, so:
var tasks = new List<ITask>();
foreach (string taskName in taskNames)
{
var task = MockRepository.GenerateStub<ITask>();
task.Stub(t => t.Name).Return(taskName);
tasks.Add(task);
}
return tasks;
The problem is that each stub object is all the same concrete type. Normally this is fine, but I have a case where I want to test each one being a different type. Can I somehow configure Rhino Mocks to do this, in this case?
EDIT:
The "you-must-be-doing-it-wrong-crew" are out in force today. Since you all seem to think I need to justify my use-case before you can take a stab at answering my question, here's what I'm doing:
ITask is in my domain model, so it's part of my business layer.
I have logic in a higher level (presentation) layer that takes an ITask as an argument.
The presentation layer logic normally executes a default Strategy on the ITask, but there can be special cases where we need to use a different Strategy, and the Strategy to use depends entirely upon the concrete type of the ITask object.
The regular Strategy pattern doesn't work here because that requires my concrete ITask objects to know about a layer above them.
Decorators still have to know about the concrete type of the object they decorate, and have to be applied either at construction time (wrong layer for this case) or when used, but then that leaves me with the same problem - applying a decorator based on concrete type.
I decided to use the same pattern used by DataTemplates (and the DataType attribute) in WPF. That is, given an object from a lower layer, see if anyone's registered a Strategy to handle that type, and if so, use it. Otherwise, use a default Strategy.
So, I hope you can see why I need the test logic. So far I've had to write my own Stub factory that generates from a limited pool of concrete ITask types. It works, but I'd rather let Rhino Mocks do it for me.
You could add a ITask.Type property.
The code which is interested in the type behind the interface should then use this property instead of calling GetType(). In your tests, it then becomes trivial to take control of what the Type property returns for any given ITask stub.

Why factory method not taking parameter in GoF Factory Method

In the Factory Method Design pattern of GoF, I can see that there is no parameter accepted by the FactoryMethod() method. My understanding is that the FactoryMethod should be passed a parameter that will be used in the switch case and then based upon the value in the switch case, different class objects are instantiated and returned back to the caller. My questions in summary are as follows:
1) Should I implement factory method pattern, exactly in the same way defined by GoF. I am also referring to UML diagram given at www.dofactory.com for Factory Method pattern).
2) Why is the factory method pattern of GoF not shown accepting parameter?
1) Should I implement factory method
pattern, exactly in the same way
defined by GoF. I am also referring to
UML diagram given at www.dofactory.com
for Factory Method pattern).
Do whatever makes sense to you. Patterns are just guidelines, not categorical laws of nature.
More than that, the patterns in GoF are not comprehensive. You'll find yourself discovering and implementing patterns which never appear in the book, nor even have a name. And that's a good thing.
2) Why is the factory method pattern
of GoF not shown accepting parameter?
The factory method pattern is simply a special instance of a derived class. In particular, you have an abstract class with an abstract method, and any number of derived classes which implement the method. Usually, this implemented method returns some other type of object -- this is what makes it a creational pattern.
So, using the sample on DoFactory.com, the classes return a canned set of objects. Nothing in principle prevents users from passing in some parameter to the factory method.
My understanding is that the
FactoryMethod should be passed a
parameter that will be used in the
switch case and then based upon the
value in the switch case, different
class objects are instantiated and
returned back to the caller.
You can certainly implement it that way if that makes sense to you.
2) Why is the factory method pattern
of GoF not shown accepting parameter?
In object-oriented programming, your methods should do one clearly-defined thing. Passing in some kind of value to switch on is called "alternate cohesion": instead the method should be into multiple methods, one for each case. For example:
createVeggie(veggieType)
would be split into
createBroccoli()
createCelery()
createCollaredGreens()
This makes your class interface cleaner, promotes easier modification, and improves compile-time checking.
Also, be careful that you are not violating Factory Method's intent: it is actually to avoid having calling code know which object is created. As Juliet says, you may implement something like this, but then it's no longer GoF Factory Method and does not have the same advantages.