Factory Design Pattern with only one concrete class type - oop

Hi there I hope I am able to explain myself clear enough with this problem I have been really confused about.
I have a concrete class called UTModule, it is not subclassed at all, but it is composed of several different abstract objects (for example UTListener, UTRenderer, UTDeliverer) the instantiation of these abstract classes to concrete objects defines the behaviour of my completed UTModule object.
The question I am asking is that, every example I see for the factory design pattern is in regards to an abstract object that is subclassed, whereas my object is a concrete class who's behaviour is decided by its composition.
Am I supposed to create a factory for each of my composite abstract objects? Or just create one factory that creates my UTModule, with the correct composite objects depending on the clients request?
Thanks in advance!

I feel like using the Abstract factory pattern is a clear solution for you.
Lets take UTModule as a abstract factory class which has methods to create a Factory of the Other Objects like "UTListener, UTRenderer, UTDeliverer"
Some additional interface is required for each UTListener, UTRenderer, UTDeliverer and respective factory class for each family.
UTModule add all require method to return the factory of the family you are looking.
For More details and example please follow OODesgin

Related

Why is factory method a class pattern, while an abstract factory an object pattern?

From GOF book:
Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance,
so they are static-fixed at compile-time. Object patterns deal
with object relationships, which can be changed at run-time and
are more dynamic. Almost all patterns use inheritance to some extent.
So the only patterns labeled "class patterns" are those that focus on
class relationships.
Why is factory method a class pattern, and abstract factory an object pattern, given that they seem to be very similar patterns?
Thanks.
Factory Method and Abstract Factory are similar in intent, but wildly different in implementation (you might even say opposite). In other words, these patterns represent different ways of solving the same problem (instantiation).
The GoF says,
We classify design patterns by two criteria. The first criterion,
called purpose, reflects what a pattern does.
Because their intent is similar (i.e. they have the same purpose) these two patterns are both classified as creational.
The GoF goes on to say,
The second criterion, called scope, specifies whether the pattern applies
primarily to classes or to objects.
This leads into the quote from the OP, where class and object scope are each defined. Because Factory Method's implementation focuses on inheritance (a class relationship) while Abstract Factory's implementation focuses on composition (an object relationship) these two patterns are classified under opposing scopes.
The definitions and implementations of these two patterns can be found in numerous other SO threads, so I will not repeat them here. I have also touched on the composition vs. inheritance question in these two patterns elsewhere.
The GOF book says
Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate.
What does this mean? Let's take a look at the example that the book shows.
In the example a framework defines the Application interface to let others implement it. This means that I can implement e.g. a MyApplication or MyOtherApplication like this:
public class MyApplication extends Application {
protected Document createDocument() {
return new MyDocument();
}
}
public class MyOtherApplication extends Application {
protected Document createDocument() {
return new MyOtherDocument();
}
}
When the framework starts it might choose one of these implementations depending on what it finds on the classpath.
But it means that after the framework has instantiated either MyApplication or MyOtherApplication the way a document is created is fix. The way a document is created can not be changed anymore at runtime for the Application instance. There is no setter or anything else that you can use to change the way the Document is created. Thus it is also called a virtual constructor and thus it is a class pattern.
Abstract Factory
In contrast to the factory method an abstract factory can be changed at runtime and thus the way the objects it creates. That's why they say it is an object pattern.
A abstract factory is also responsible for creating
... families of related or dependent objects ...
This is also a difference to the factory method aka. virtual constructor.
Factory patterns are probably better to place in its own category. But logic behind object/class division maybe quite simple. Factory method in its minimal form is static (not configurable), just like classes are. But abstract factory result (object they produce) class depends on some input data, and since it is dynamic effect it should be put into object pattern category.

Why Interfaces can not have constructor but abstract classes have constructor

We all know that we can not create the object of both interface and abstract class.But why we are allowed to have constructor in abstract class but not in interface? object of both can not be created.I want very straight forward answer not very complex answer.
Interfaces (at least in .NET and Java, for example) are meant to serve exclusively as what they are named for - to guarantee a certain interface (i.e. set of (public) members) in all implementing classes.
Interfaces are not supposed to have a state, and they are not even supposed to define something like an initial state. Without an initial state, nothing reasonable would be left for a constructor of an interface to be done.
An interface is just a set of member signatures that must be fulfilled by an implementation. Why you can't define constructors? Because constructors are an implementation detail.
Let's say that when you want to hire someone you're not focused on who's the candidate but what can do the candidate (this is a simplification). Does your candidate own desired tech background? Can your candidate do teamwork? From OOP's point of view, you know what a candidate must fulfill to work with you. Therefore, I don't care about a candidate's mother and when/how candidate was born: I care about what properties and behaviors are acceptable for me today. So you would define an interface like CanWorkOnMyCompany for that matter.
In the other hand, an abstract class is a regular class on which some members are signatures and a derived class must provide an implementation to them. That is, you can't instantiate an abstract class because it's not fully implemented.
Probably you could argue that an abstract class can provide no abstract member, but it's not their purpose.
Constructors are for initializing the state of a new instance.
Abstract classes can define state and can have constructors to initialize it.
Interfaces can't define any state and so have no need for constructors.

OOP Principle Differences between Interfaces and Abstract Classes

I understand that Abstract Classes are classes that contain declared methods that do not all necessarily have a specified implementation because the code would have to be declared in the child class instead but Im finding it difficult to understand the OOP concept behind the introduction of Interfaces.
What are the architectural and principle differences between interfaces and abstract classes if the abstract class has no defined methods and states (Aside from the fact that abstract classes can have constructors)?
In addition, why should anyone use abstract classes and interfaces in the first place? I understand that it adds restrictions to your code not allowing people to defined subclasses without specified methods but the code would work in the exact same way if the non implemented declared methods were not present in the interface and abstract class. So what is the implied benefit of writing methods with no implementation only to implement it later in the subclass?
I have seen many posts on Interface vs Abstract Classes but im interested in the principle differences between the two, not their functional differences.
Coming back to my own question after a year, I have discovered the answer that I wanted.
A class, regardless of being abstract or not, always tries to define/design what entities look like from their behaviour to their states. In the case of an abstract class, we are modelling an idea/entity that we do not want to be instantiated during run time. Example, if we had an app about dogs and cats, we may want to define what an animal is and then extend this idea to define what a dog/cat is by extending our base animal class. An animal object will never be instantiated but a dog/cat will.
An interface on the other hand are a set of methods that represents some form of interactions to be expected from any class. As long as a class implements an interface, you know what methods to expect from it. Thus, you can have two entities (classes) that do not relate to one another that implement the same interface. Example, a dog and person class may both implement a 'digest' interface. This means that they are all able to digest food as we have explicitly stated what functions to expect in the interface to enable food digestion behaviour. Obviously the details of the implementation differs thus the functions defined in the interface are outlined in the classes implementing them.

How do you model this in a class diagram?

Say I have an interface Interface and a concrete class ConcreteClass that implements Interface. Now consider a third class MyClass. If instances of MyClass hold a reference to ConcreteClass:
Interface ref = new ConcreteClass();
then should I associate MyClass with Interface or ConcreteClass in UML class diagram?
Thanks
That depends on what the public interface of MyClass defines.
If the public interface makes an Interface available, then you should link to that on the diagram. This would be the usual approach as the Interface is the general type and specifies the contract. Unless you have a reason to limit to ConcreteClass, don't.
If the public interface makes a ConcreteClass available, then you should link to that on the diagram.
The fact that at runtime a variable of type Interface actually holds an instance of ConcreteClass is beside the point. The diagram represents the relationships.
Solely with the Interface. The point is that you want the behavior of the interface. Whatever the implementation is of that interface is for the picture of no importance. MyClass has a relation with the interface, not with the implementation of the interface.
This principle is called Design By Interface. In the answer given by nakosspy is it his first picture. But it would even be better to leave the implementation of ConcreteClass out of the picture. The implementation is of no importance at that conceptual level. If there is a variable pointing to an interface, then is it obvious to the educated reader that there should be a concrete implementation as well.
If you would make a reference to the ConcreteClass then would you have to change the diagram everytime you change the implementation of the interface. That is not what you want. It is bad coding practice and bad uml practice.
It is good coding practice to separate the declaration of the relationship between MyClass and the Interface and the practical implementation of the Interface. By example:
Interface ref = new ConcreteClass();
should never happen in the class MyClass.
You should have something like this instead:
class MyClass
Interface ref;
setRef(){
ref = InterfaceImplementation();
}
}
This way can you change the implementation of Interface without changing one line of code in MyClass. Altough this might look much ado when you write one class, think of it when you are managing hundreds of classes.
So: it depends.
It's equally legal to associate MyClass with ConcreteClass or Interface. You won't find the answer to your question in the UML spec. Why? Because the answer lies in your problem domain, not the modelling language.
Consider two contrived examples to illustrate the point.
Example 1: Association between Classes
Substitute:
ICanBark for Interface
Dog for ConcreteClass
Trainer for MyClass
Let's assume the association we want to capture is Trains, i.e.
Each Trainer trains many Dogs
Each Dog is trained by at most one Trainer
In this case the association exists because of the 'Dogginess', not the 'Barkiness'. So it properly exists between the two classes.
Example 2: Association between Class and Interface
Substitute:
ILogger for Interface
FileLogger for ConcreteClass
Application for MyClass
In this case the relationship is about the 'Logginess', not the 'Fileness'. Application shouldn't care how the interface is implemented; it just wants a way to log messages. So the Association exists between the Class and the Interface
Summary
As is nearly always the case with Associations, the key to solving the problem lies in the problem domain itself - not the modelling language.
hth.
There are 2 ways to present the ref variable of MyClass: You can present it as attribute or as association. Then there are two alternative notations for the Interface interface: Square with the interface stereotype or circle. This makes 2*2=4 alternatives.
Show ref as association and use square interface notation.
Here you can't show the initial value that ref takes. That's because you can't show default values in associations.
Show ref as association but use the circle notation for the Interface.
As it was with the previous alternative, again here you can't show the initial value.
Show ref as attribute and use square interface notation.
Here you can show the default value, because you can do that for attributes. The relationship between MyClass and Interface is presented as a dependency. The same happens for the dependency between MyClass and ConcreteClass.
Note that this dependency (MyClass depends on ConcreteClass) can be presented also in the alternatives 1 and 2, you can add a dependency arrow (dashed) pointing from MyClass to ConcreteClass.
Show ref as attribute and use circle interface notation.
Again here you can show the default value.
If we count also the alternatives derived from presenting or not the dependencies, then there are at least 6 ways to present the same thing. Now the question is which to chose.
It depends on what do you want to visualize with the diagram and for whom the diagram is intended. In this case if the initialization of ref is the message, then you should use an alternative that presents it. If it's less important, then you might prefer a diagram that shows ref as association.
In a real problem you have more elements, so it makes much more alternatives. It's always up to you to decide what to present and how.
EDIT: Some references to help you understand the notation of interface implementation.
According to wikipedia:
A realization is a relationship between classes, interfaces,
components, and packages that connects a client element with a
supplier element. A realization relationship between classes and
interfaces and between components and interfaces shows that the class
realizes the operations offered by the interface.
You can find some quick reference examples and a lot of information at uml-diagrams.org.
This excellent answer Explanation of the UML arrows will help you with more examples.
Here you can also find some more info on realization.
You can define reference to concrete class as:
Attribute typed as Interface (or ConcreteClass) defined in MyClass, or
Association between MyClass and Interface (or ConcreteClass).
no more options are avialable

Object Orientation - Where to place this Interface Declaration

I have a few questions for you wise people involving OO design with Interfaces and abstract base classes. Consider the following scenario:
I have an abstract bass class "DataObjectBase" and a derived class "UserDataObject." I also have an interface "IDataObject." The interface of course exposes all of the public methods and properties that my Data Objects must expose, and you can probably guess that the abstract base implements the methods and properties common to all Data Objects.
My question is, if the abstract bass class DataObjectBase implements everything specified in the interface IDataObject, should the interface be declared on the base class, or on the derived classes(s)?
In C# interfaces declared on the base class are implicity applied to the derived classes, but is this the best practice? It seems to me that implementing the interface on the base class makes it less obvious that the derived class implements the interface, but then again requires the Interface to be specified for each derived class.
Additionally, if the base class was NOT abstract, would the reccomendation change?
A second sub-question: If the base class implements all of the methods/properties of the IDataObject interface, is the interface even needed? The base class typename can simply be used in place of the interface name, ie:
private DataObjectBase _dataObject;
private IDataObject _dataObject;
In the above example (where again the base implements everything exposed by the interface) both can be assigned the same derived types. Personally I always use the interface in these situations, but I am intrested in hearing peoples thoughts.
Thanks in advance.
My way of thinking about such problems is to consider the different people reading the code, the "roles" if you like. Also consider the overall maintainability of the system.
First there is some code expecting to use the Interface. It's written in terms of the interface, the author has (should have) no interest in the implementation. That's why we provide the Interface class. From that perspective the Abstract Base Class is just one of many possible implementation hierarchies. Don't tell this role about implementation details. Keep the Interface.
Then we have the role who is designing an implementation. They come up with one possible approach and discover some variations, so they want to pull common code together. Abstract Base Class - fill in the common stuff here, let detailed implementers fill in the gaps. Help them by providing abstract methods saying "your code goes here". Note that these methods need not only be the ones in the Interface. Also note that this Abstract Base Class might even implement more that one Interface! (eg. It's CleverThingWorker but also a IntermediateWorkPersister.)
Then we have the role who actually do the fine detailed implementation. Fill in the gaps here. Dead easy to understand. In this case you don't even need to consider the Interface as such. Your job is to make that abstract class concrete.
Bottom line ... I use both Interfaces and Base classes. You put the Interface on the Base Class. We don't add value by adding it to the implementation class.
If your user classes will always inherit from one base class, then you don't need the interface. If there is a possibility that you will have classes that match the interface but are not derived from the base class, then use the interface.
As for the interface being hidden in the base class and hence not immediately visible in the user class, this is normal and can be dealt withg by the compiler. This is also where good naming conventions come in - your UserDataObject has a name that matches IDataObject, as does DataObjectBase. You could add a comment to the class file that says it inherits from IDataObject, but it will be visible that it inherits from DataObjectBase, which in turn looks like it inherits from IDataObject by its name.
The other thing that needs to be mentioned is that the use of interfaces makes it easier to implement automated tests.
Say, for example, that one of the methods of the interface is supposed to throw a exception - such as 'DatabaseConnectionLostException' - and you want to test client code to check that it behaves correctly in such a situation.
It is a simple matter to provide an implementation of the interface that throws the exception, allowing the test to be written.
If you used the abstract base class instead of the interface, this operation would be quite a bit trickier (OK, you can use Mocks, but the interface solution is much cleaner)