I am new to design patterns , I am learning Observer pattern for that I went to many sites ,where I found the below UML diagram
So my question is on the UML or class design.If the purpose of the observer pattern is to notify the observers about the change in state of subject/object, Why the subject needs to be abstract can’t it be a ConcreteSubject directly as shown below:
What are the disadvantages or violations if we create a Subject as ConcreteSubject.
I understand that the purpose of defining the abstract subject class is to provide a base implementation of the properties and methods needed for the Observers to subscribe and receive notifications.
A more generic alternative would be to provide an interface. Or perhaps the abstract class is in fact implementing a more generic interface that only defines the methods that have to be implemented.
In other words the advantage of providing an interface is that you don't need to know the class that implements it.
The advantage of using an abstract class is that you have a base implementation of the methods needed to add or remove observers and to send them notifications. And you take advantage of this by deriving the class.
Making Concrete Observer dependent upon Concrete subject will solve one problem [Type casting in update method as update(ConcreteSubject cs)] but at the cost of generic nature of Pattern.
Concrete Subject and Abstract Subject (Observable) have clear demarcation of responsibilities namely - Implement Business logic and be an Observable across application and take care of Observers.
In case we avoid using Subject, every business class requiring Observers (May be added down the line) will have to repeat the code of Subject. (Extending one Concrete Subject from Another Concrete Subject is OO violation).
Best way will be to use Abstract Subject and keep extensions and code reuse open.
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.
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.
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.
From a picture, Can i use inheritance instead of implement an interface?
I mean change from "ConcreteStrategyA and ConcreteStrategyB implements Strategy Interface" to "ConcreteStrategyA and ConcreteStrategyB extends Strategy Class"
Is it still work well or have some problem?
If it still work well my next question is "Why most people prefer to use interface?"
Well technically from a Design pattern perspective with the Strategy pattern, the concrete Strategies need to implement (I mean write code for, not the interface implements thing) a common contract which the Strategy Context is aware of. This is the primary backbone of Strategy pattern philosophy. The adherence to the common contract is what allows the Strategy context to replace the concrete strategies based on some runtime feature. This pattern ideology is what we loosely call Polymorphism in OOP parlance.
Now in Java you can implement his polymorphic strategy either as an interface or as inheritance. For interface you have given the example in the question itself. For inheritance as long as the contract holds between subclasses (something like a base abstract class with an abstract contract which subclasses implement to provide concrete strategy implementations) you can implement Strategy pattern in inheritance as well.
Now thinking about it from OOP perspective. For OOP inheritance is something which a subclass inherits from a super class. The subclass automatically owns and thus demonstrates that inherited generic behavior but it has a choice to make that behavior more specific to its own type. Thus multiple subclasses can override the same behavior and make bits of it more specific to their use. But this chain becomes cumbersome to manage when it gets too long or when subclasses try to inherit the behaviors which don't apply to them logically.
Thus it makes more sense to implement Strategy pattern using interfaces as against inheritance.
Absolutely. Inheritance is most often used with an abstract base class, when you want your derived strategies to share some common code.
People prefer to use interfaces or abstract classes over concrete base classes because :
With a Dependency Inversion approach, a class needs loose coupling to its Strategy. It only needs to know that the Strategy fulfills a contract, but doesn't want to know about its implementation details. Interfaces and abstract classes are an elegant and minimal way to define a contract without specifying the implementation.
It doesn't make sense to instantiate the base Strategy class most of the time, because it's a general, abstract concept -- in fact, it's better if you forbid instantiating it.
There are no technical problems.
However, a class can only extend one base class but it can implement multiple interfaces. So if you want to, let's say, change your inheritance structure in the future it is easier if you choose to implement an interface instead.
As you know a design pattern is "a general solution to a commonly occurring problem". It just describe a general solution without indications concerning implementation details.
If your problem requires a class in place of the interface, there is nothing wrong replacing it with a concrete (or abstract) class.
Using an interface in the pattern UML is a way to say: "you have to expose this set of public methods".
So, no problem using your approach. As an alternative you could leave the Strategy interface and implement it in a StrategyImpl class, then you can inherit this class in your ConcreteStrategyA and ConcreteStrategyB classes.
If interfaces have empty methods (implicit abstract method) then what is its use? Why do we say it reduces the code and provides re-usability? Give me a real life example of using an interface that shows the difference between an abstract class and an interface.
Interface is more like a contract. It doesn't provide any implementation reuse as such. Which actually makes your code de-coupled from implementation. Having a abstract class with ALL the methods abstract provides the same benefit (if we ignore the issue of multiple inheritance).
For a really good example take a look at Java Collections and how things are loosely coupled using interfaces for Collection, Map and Lists.
Because of the terminology you are using, I am going to assume you are talking about Java.
An interface is useful in lieu of an abstract class because a class can only inherit from a single class, but can implement multiple interfaces.
An interface is a contract between parts of the program. It says that one part of the program has certain expectations about classes that implement this interface. As long as those classes uphold that interface contract, the other parts of the program don't care how that contract is implemented, just that it is implemented.
It allows for polymorphism and for the reuse of code. For instance, (with respect to Java), you can take the List interface. You can write code that interfaces with a List object where you don't care about the implementation of the List. Your code then can be used with a LinkedList or an ArrayList or any other type of list that it may deal with, and it should be able to manage well enough. You can write code now that has certain expectations through this List interface contract, and 15 years down the road someone can use the latest technologies to create their own List implementation and your code will be able to use it.
Abstract class lets you describe fields and non abstract methods. It does not limit you to simply describing interface, it involves some logic. Interface on other hand does what it says and has nothing to do with logic. From client code side, you have no worries about implementation and how stuff works. It lets you exchange one interface realization with other without additional code.
On realization code side, interface lets you perform multiple "inheritance".
I like to call these types of features "implied code documentation". Using an interface can communicate a lot of information to other developers who will be working on your project, and this information can help prevent a lot of headaches.
For instance, if a class implements an interface that has 2 methods, and I'm new to the project, that may tell me that the developer who wrote those methods don't want the method signature to change.
Think about the Dog class and the Cat class that both implement the interface Sociable, where there are methods walk(int speed), sit(), layDown(), bite(int degree).
If we have a Dog class and a Cat class that implement these methods and there are dependencies on them, changing the method signature of one could have some negative effects.
Interfaces are a way to help describe a class. In this example, a Sociable Dog and a Sociable Cat have a lot in common.
As far as reusability goes, your classes become reusable because it's harder for others to come in and change the contract defined in the method signature.
Lastly, while a class can only subclass one class, it can implement multiple interfaces. Thus, the advantage of using an interface is that I can have a Dog that implements Big and Sociable, and a Cat that implements Small and Sociable.