2 ms·
I don't understand, I'm afraid. How does function passing negate the need to choose between multiple implementors of an interface?
by AndrewDucker 15y ago
I don't understand, I'm afraid. How does function passing negate the need to choose between multiple implementors of an interface?
- fleitz 15y agoThe interface of a factory pattern is generally a single method, so most factory patterns are an interface with a single function. Normally a factory class looks like this: class MyFooFactory : FooFactory { Foo createFoo() { return new MyKindOfFoo(); } } createFoo has a type of () -> Foo, that is to say a function that takes no parameters an returns an object of class Foo. Sometimes the pattern is String -> Foo, but the more general case is () -> T When you need to use a factory you'll create it and then pass it to the object like: FooFactory f = new MyFooFactory(); FooUser fu = new FooUser(f); fu.doSomething(); And FooUser will have some method in it that does something like public doSomething() { Foo foo = fooFactory.createFoo(); // does something with the foo. } If FooUser took a parameter of () -> Foo instead of FooFactory your code would now look like this: FooUser fu = new FooUser(() => new MyKindOfFoo()); fu.doSomething();
- AndrewDucker 15y agoYes, in the case where a Factory class contains one method that takes no parameters and just contains a "new" call, you can get rid of the class and pass in the method. I was more thinking of the kind of thing I mentioned in my earlier comment, where you have an IWriter interface, a bunch of different classes that implement it, and a Factory class that passes back the correct one for different situations. I completely agree that a whole class that does nothing but call "new" is complete overkill, and almost certainly just there to fit into a pattern because someone thinks that Patterns Are Awesome. The kind of thing I'm thinking of is this: https://github.com/andrewducker/FeedThisToThat/blob/master/FeedThisToThat/src/feedthistothat/Writers/WriterFactory.java https://github.com/andrewducker/FeedThisToThat/blob/master/F...