Sei sulla pagina 1di 9

SAD LAB 2 January 18

Object: Create Abstract Design Pattern In Java

Theory
Design Pattern
Pattern
When they find a good solution, they use it again and again – pattern. A designer who is familiar with
such patterns can apply them immediately to design problems without having to rediscover them.

What is a design pattern?


Each pattern describes a problem which occurs over and over again in our environment, and then
describes the core of the solution to that problem, in such a way that you can use this solution a million
times over, without ever doing it the same way twice"

[Christopher Alexander]

Design patterns are class combinations and accompanying algorithms that fulfill common design
purposes. Design patterns are descriptions of communicating objects and classes that are customized to
solve a general design problem in a particular context.

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem
in software design. A design pattern is not a finished design that can be transformed directly into code. It
is a description or template for how to solve a problem that can be used in many different situations.
Object-oriented design patterns typically show relationships and interactions between classes or objects,
without specifying the final application classes or objects that are involved

Types of Design Patterns


There are mainly three types of design patterns, which are further divided into their sub-parts:

1. Creational Design Pattern


1. Factory Pattern
2. Abstract Factory Pattern
3. Singleton Pattern
4. Prototype Pattern
5. Builder Pattern.
SAD LAB 2 January 18

2. Structural Design Pattern


1. Adapter Pattern
2. Bridge Pattern
3. Composite Pattern
4. Decorator Pattern
5. Facade Pattern
6. Flyweight Pattern
7. Proxy Pattern

3. Behavioral Design Pattern


1. Chain Of Responsibility Pattern
2. Command Pattern
3. Interpreter Pattern
4. Iterator Pattern
5. Mediator Pattern
6. Memento Pattern
7. Observer Pattern
8. State Pattern
9. Strategy Pattern
10. Template Pattern
11. Visitor Pattern
SAD LAB 2 January 18

Creational design patterns


Creational design patterns are concerned with the way of creating objects. These design
patterns are used when a decision must be made at the time of instantiation of a class (i.e.
creating an object of a class).

But everyone knows an object is created by using new keyword in java. For example:

StudentRecord s1=new StudentRecord();

Hard-Coded code is not the good programming approach. Here, we are creating the instance by
using the new keyword. Sometimes, the nature of the object must be changed according to the
nature of the program. In such cases, we must get the help of creational design patterns to
provide more general and flexible approach.

Structural design patterns


Structural design patterns are concerned with how classes and objects can be composed, to form
larger structures.
The structural design patterns simplifies the structure by identifying the relationships.
These patterns focus on, how the classes inherit from each other and how they are composed
from other classes.

Behavioral Design Patterns


Behavioral design patterns are concerned with the interaction and responsibility of objects.
In these design patterns, the interaction between the objects should be in such a way that
they can easily talk to each other and still should be loosely coupled.
That means the implementation and the client should be loosely coupled in order to avoid hard
coding and dependencies.
SAD LAB 2 January 18

Observer Patterns
GoF Definition: Define a one-to-many dependency between objects so that when
one object changes state, all its dependents are notified and updated automatically.

Concept
In this pattern, there are many observers (objects) which are observing a particular subject
(object). Observers are basically interested and want to be notified when there is a change made
inside that subject. So, they register themselves to that subject. When they lose interest in the
subject they simply unregister from the subject. Sometimes this model is also referred to as the
Publisher-Subscriber model.

Important Points on Observer Design Pattern


 Subject provides interface for observers to register and unregister themselves with the subject.
 Subject knows who its subscribers are.
 Multiple observers can subscribe for notifications.
 Subject publishes the notifications.
 Subject just sends the notification saying the state has changed. It does not pass any state
information.
 Once the notification is received from subject, observers call the subject and get data that is
changed.

The above last two points are not strictly followed in observer design pattern implementation.
Along with the notification, state is also passed in some implementation so that the observer need
not query back to know the status. It is better not to do this way.

Scenario for Observer Pattern Usage


 When multiple objects depend on state of one object and all these multiple objects should
be in sync with the state of this one object then observer design pattern is the right choice
to apply.
 Consider an excel sheet, data is shown to the user in different views. Generally data is is
shown in grid cells and as required different graphs, charts can be created for same data.
Underlying data is same and when that data (subject) state changes all the different view
are updated.
SAD LAB 2 January 18

Real-Life Example
We can think about a celebrity who has many fans. Each of these fans wants to get all the latest
updates of his/her favorite celebrity. So, he/she can follow the celebrity as long as his/her interest
persists. When he loses interest, he simply stops following that celebrity. Here we can think of
the fan as an observer and the celebrity as a subject.

Computer World Example


In the world of computer science, consider a simple UI-based example, where this UI is
connected with some database (or business logic). A user can execute some query through that
UI and after searching the database, the result is reflected back in the UI. In most of the cases we
segregate the UI with the database. If a change occurs in the database, the UI should be notified
so that it can update its display according to the change.

Illustration
Now let us directly enter into our simple example. Here I have created one observer (though you can
create more) and one subject. The subject maintains a list for all of its observers (though here we have
only one for simplicity). Our observer here wants to be notified when the flag value changes in the
subject. With the output, you will discover that the observer is getting the notifications when the flag
value changed to 5 or 25. But there is no notification when the flag value changed to 50 because by this
time the observer has unregistered himself from the subject.

UML diagram
SAD LAB 2 January 18

Implementation
package observer.pattern.demo;
import java.util.*;

class Observer
{
public void update()
{
System.out.println("flag value changed in Subject");
}
}

interface ISubject
{
void register(Observer o);
void unregister( Observer o);
void notifyObservers();
}
class Subject implements ISubject
{
List<Observer> observerList = new ArrayList<Observer>();
private int _flag;
public int getFlag()
{
return _flag;
}
public void setFlag(int _flag)
{
this._flag=_flag;
//flag value changed .So notify observer(s)
notifyObservers();
}
@Override
public void register(Observer o)
{
observerList.add(o);
}
@Override
public void unregister(Observer o)
{
observerList.remove(o);
}
@Override
public void notifyObservers()
{
for(int i=0;i<observerList.size();i++)
{
SAD LAB 2 January 18

observerList.get(i).update();
}
}
}
class ObserverPatternEx
{
public static void main(String[] args)
{
System.out.println("***Observer Pattern Demo***\n");
Observer o1 = new Observer();
Subject sub1 = new Subject();
sub1.register(o1);
System.out.println("Setting Flag = 5 ");
sub1.setFlag(5);
System.out.println("Setting Flag = 25 ");
sub1.setFlag(25);
sub1.unregister(o1);
//No notification this time to o1 .Since it is unregistered.
System.out.println("Setting Flag = 50 ");
sub1.setFlag(50);
}
}

Lab Task
Create Java Program based on following UML Diagram using Observer Pattern.

Classes Required
Observer.java
User.java
Subject.java
Blog.java
ObserverDesignPattern.java
Output Should Be looks Like !!!
SAD LAB 2 January 18

OutPut!!!
No New Article!
State change reported by Subject.
State change reported by Subject.
Observer Design Pattern
SAD LAB 2 January 18

Potrebbero piacerti anche