Apparently, singletons are bad, and a factory method is recommended. I'm wondering if a singleton toolbox is any better than a singleton.
In my opinion, It's really weak to think that singletons are bad,factory methods are good.
Each of them has preferences. As consequence, I'm sure that there is misunderstanding here.
I know that wikipedia is not the best source. But check out the definition of them. The range of situations are not the same for these patterns.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created. This is done by creating objects via calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
Related
GoF book states that there are two ways to implement Factory Method:
Consider the following issues when applying the Factory Method pattern:
Two major varieties. The two main variations of the Factory Method pattern are the case when the Creator class is an abstract
class and does not provide an implementation for the factory method it
declares, and the case when the Creator is a concrete class and
provides a default implementation for the factory method. It’s also
possible to have an abstract class that defines a default
implementation, but this is less common. The first case requires
subclasses to define an implementation, because there’s no reasonable
default. It gets around the dilemma of having to instantiate
unforeseeable classes. In the second case, the concrete Creator uses
the factory method primarily for flexibility. It’s following a rule
that says, “Create objects in a separate operation so that subclasses
can override the way they’re created.” This rule ensures that
designers of subclasses can change the class of objects their parent
class instantiates if necessary.
Parameterized factory methods. Another variation on the pattern lets the factory method create multiple kinds of products. The factory
method takes a parameter that identifies the kind of object to create.
All objects the factory method creates will share the Product
interface. In the Document example, Application might support
different kinds of Documents. You pass CreateDocument an extra
parameter to specify the kind of document to create.
Design Patterns (Design Patterns: Elements of Reusable Object-Oriented Software)
In what cases should I use one approach instead of another. What the benefits and drawbacks when I prefer one approach instead of another?
Thanks in advance.
Kudos for reading the book. Most people attempt #2 believing that is the Factory Method pattern, when in fact #1 claims to describe the two major varieties.
So we're actually dealing with three slightly different versions of the pattern in the quoted text, though only two of them are numbered. The differences between these versions are based on how much information the Creator has about which Product implementation it wants.
A Creator with an abstract Factory Method knows nothing about the Product implementation and leaves everything up to the ConcreteCreator.
A Creator with a default Factory Method knows what Product implementation it wants most of the time, but not always; so it allows a ConcreteCreator to override the default.
A Creator with a parameterized Factory Method has a menu of Product implementations to choose from and decides which one to ask the ConcreteCreator for.
So in each consecutive version, the Creator has progressively more information about the Product implementations and more logic concerning how the implementation is chosen.
In the Factory Method pattern, a Creator delegates responsibility for creating objects to its child classes because it, "can't anticipate the class of objects it must create." (page 108) Based on the different varieties, we can see how the pattern changes slightly when a Creator can anticipate some information about the class of objects to create.
The version you choose depends on how much you know about the Product implementations at compile time.
The intent of the Abstract Factory design pattern is to
"Define an interface for creating families of related or dependent objects
without specifying their concrete classes." [GoF]
This is a short statement of what the design pattern does (solution),
but it isn't clear what particular design problems it solves.
I would define the
following design, refactoring, and test problems,
but I am not sure whether this list is complete.
Design Problems
Creating Objects and Object Families
How can a system support creating different families of objects
so that which family to create can be selected and changed dynamically?
How can a system be configured with a family of objects?
And how can the whole family of objects be exchanged dynamically?
How can the way objects are created (which classes are instantiated)
be changed independently?
How can a system be independent of how its objects are created?
Creating Consistent Object Families
How can be ensured that a system creates objects from only one of different
families at a time?
Refactoring Problems
Distributed Creation Code
How can instantiating concrete classes throughout an application be refactored?
How can creation code that is distributed across many classes be centralized?
Testing Problems
Unit Tests
How can creating objects and object families be designd
so that object creation can be mocked easily for unit testing?
Keeping the long story short - if in the future a new group of objects is introduced in your current OO design, a new factory will be derived from AbstractFactory, encapsulating creation of all concrete objects related to that group. It’s that simple.
As addition is also important to say that
“This pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".
In short we need a class here which will do all the common tasks and expose a virtual or abstract function.
So creating AbstractFactory will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our SubFactoryA and SubFactoryB. By doing so - you'll achieve common architecture, propagate minimum/default set of practices, standards etc. Here is a very good article about all this.
I have an object that I would like to create. This object is composed of other objects that I don't want the client class to be responsible for creating. There are lots of validation rules that must pass before the object can be created.
So I would like to abstract away the creation of this complex object into a "factory" class. I have 2 questions really, the first is purely about semantics:-
What should I call the class which is creating my object? The factory method pattern and abstract factory pattern are both related to abstracting away creation of concrete classes of different types. However, I'm creating an object of a single type, so using the term factory might be confusing?
Is this an appropriate solution? Are there any patterns/examples of this being done?
Thanks in advance for any help/guidance.
You can use the term factory because we all use it in its broadest sense unless we use a more unique name like Factory Method design pattern or Abstract Factory design pattern.
Builder pattern is typically used if you have an object build process that should still be used if the same master steps should be used in creating different types of objects. But in your case you just have one type. So there's no need for a better solution since there's no special problem to solve. Just do the validation in the simplest form you can.
It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.
This is a pretty general question, but I was wondering today about delegates. At this point I don't really have a specific time I do use them or don't use them - aside from obvious cases, like passing selections from a picker or tableview stuff. For example, if there's a situation where I can pass a reference to an object around and use that to call methods, is there a reason to implement a delegate? In summary, what is the delegate pattern intended for use in and when is it better to NOT use it?
Thanks for the quick and comprehensive answers! They were all extremely helpful.
The advantage of the delegate pattern is loose coupling between the delegating object and its delegate. Loose coupling improves a class's reusability in other contexts.
The delegating object doesn't have to know anything about the object it communicates with (aside from the requirement that it implement the delegate protocol) – especially not its class or what methods it has. If you later want to reuse your component in a different context or have it communicate with another object of a different class, all this object has to do is implement the delegate protocol. The delegating object does not have to be changed at all.
There is also a downside to this, of course, and that is that a bit more code is required and the code you write is not as explicit and therefore may be a bit harder to understand. Whether this (generally small) tradeoff is worth it depends on your use case. If the two objects are tightly coupled anyway and the probability of reuse in the future is low, using the delegate pattern might be overkill.
See this discussion
A delegate allows one object to send messages to another object when an event happens.
Pros
Very strict syntax. All events to be heard are clearly defined in
the delegate protocol.
Compile time Warnings / Errors if a method is not implemented as it should be by a delegate.
Protocol defined within the scope of the controller only.
Very traceable, and easy to identify flow of control within an application.
Ability to have multiple protocols defined one controller, each with different delegates.
No third party object required to maintain / monitor the communication process.
Ability to receive a returned value from a called protocol method. This means that a delegate can help provide information back
to a controller.
Cons
Many lines of code required to define: 1. the protocol definition, 2. the delegate property in the controller, and 3. the implementation of the delegate method definitions within the delegate itself.
Need to be careful to correctly set delegates to nil on object deallocation, failure to do so can cause memory crashes by calling methods on deallocated objects.
Although possible, it can be difficult and the pattern does not really lend itself to have multiple delegates of the same protocol in a controller (telling multiple objects about the same event)
The "use case" for delegation is pretty much the same as for inheritance, namely extending a class behavior in a polymorphic way.
This is how the wikipedia defines delegation:
In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.
There are, obviously, many differences between delegation and inheritance, but the biggest one is, IMO, that inheritance is a fixed (aka, compile-time) relationship between two classes, while delegation can be defined at run-time (in languages that support this). On the other hand, inheritance offers better support for polymorphism.
Delegation is a huge topic (as inheritance is), and you can read a lot about it. In the end, deciding whether using delegation or inheritance comes down to deciding whether you want an "is-a" or and "has-a" relationship, so it is not so easy to list guidelines for choosing that.
For me, basically, the decision to create a delegate comes from the observation that:
my code presents a set of homogeneous behaviors (homogeneous here means that can be recognized as having a common "nature");
those behaviors might be be "customized" for particular cases (like in, replaced by alternative behaviors).
This is my personal view and a description of the way I get to identify "delegation" patterns. It has probably much to do with the fact that my programming discipline is strongly informed by the principle of refactoring.
Really, IMO, delegation is a way to define "customization" points for your class. As an example, if you have some kind of abstract workflow, where at each step you take some action depending on certain condition; and furthermore those concrete actions could be replaced by other of another kind, then I see there the chance of reuse through delegation.
Hope this helps.