Anda di halaman 1dari 10

http://www.tutorialspoint.com/design_pattern/singleton_pattern.

htm
UNIT IV
GANG OF FOUR (GoF) DESIGN PATTERNS/ DESIGN PATTERNS:
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson und John
Vlissides published a book titled Design Patterns - Elements of Reusable Object-
Oriented Software which initiated the concept of Design Pattern in Software
development.
Design Patterns describes the recurring solutions to common problems in software
design.
3 TYPES OF DESIGN PATTERN:
Creational Pattern These design patterns provides way to create
objects while hiding the creation logic, rather
than instantiating objects directly using new
operator.
Structural Pattern These design patterns concern class and
object composition. Concept of inheritance is
used to compose interfaces and define ways
to compose objects to obtain new
functionalities.
Behavioural Pattern These design patterns are specifically
concerned with communication between
objects.

Adapter Pattern Type of Structural Pattern
Singleton Pattern Type of Creational Pattern
Factory Pattern Type of Creational Pattern
Observer Pattern Type of Behavioural Pattern

1.ADAPTER PATTERN:
Adapter pattern works as a bridge between two incompatible interfaces.i.e. it is used
to convert the programming interface of one class into another.
This type of design pattern comes under structural pattern as this pattern combines the
capability of two independent interfaces.
This pattern involves a single class which is responsible to join functionalities of
independent or incompatible interfaces.
The concept of adapter is simple, we write a class that has desired interface and then
make it communicate with the class that has a different interface.
Problem: How to resolve incompatible interfaces, or provide a stable interface to
similar components with different interfaces?
Solution: Convert the original interface of a component into another interface through
an intermediate adapter object.
A real life example could be a case of card reader which acts as an adapter between
memory card and a laptop.
You plugins the memory card into card reader and card reader into the laptop so that
memory card can be read via laptop.
We are demonstrating use of Adapter pattern via following example in which an
audio player device can play mp3 files only and wants to use an advanced audio
player capable of playing vlc and mp4 files.
Advantage:
o Resolves the problem of incompatible interfaces.
Implementation
We've an interface MediaPlayer interface and a concrete class AudioPlayer
implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio
files by default.
We're having another interface AdvancedMediaPlayer and concrete classes
implementing the AdvancedMediaPlayer interface.These classes can play vlc and
mp4 format files.
We want to make AudioPlayer to play other formats as well. To attain this, we've
created an adapter class MediaAdapter which implements the MediaPlayer interface
and uses AdvancedMediaPlayer objects to play the required format.
AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type
without knowing the actual class which can play the desired format.
AdapterPatternDemo, our demo class will use AudioPlayer class to play various
formats.

// Create interfaces for Media Player and Advanced Media Player.
interface MediaPlayer
{
public void play();
}
interface AdvancedMediaPlayer
{
public void Vlcplayer();
public void Mp4();
}
// Create concrete classes implementing the AdvancedMediaPlayer interface.
public class VlcPlayer implements AdvancedMediaPlayer
{
}
public class Mp4Player implements AdvancedMediaPlayer
{
}
// Create adapter class implementing the MediaPlayer interface.
public class MediaAdapter implements MediaPlayer
{
AdvancedMediaPlayer advancedMusicPlayer;
}
// Create concrete class implementing the MediaPlayer interface.
public class AudioPlayer implements MediaPlayer
{

}

public class AdapterPatternDemo
{
public static void main(String args[])
{

}
}

2.SINGLETON PATTERN
Singleton pattern is one of the simplest design patterns .
This type of design pattern comes under creational pattern as this pattern provides one
of the best way to create an object.
This pattern involves a single class which is responsible to creates own object while
making sure that only single object get created.
This class provides a way to access its only object which can be accessed directly
without need to instantiate the object of the class.
Problem: Exactly one instance of a class is allowed-it is singleton.Objects need a
global and single point of access.
Solution: Define a static method of the class that returns the singleton.
Advantages:
o Instance-side solution offers flexibility.
Implementation
We're going to create a SingleObject class. SingleObject class have its constructor as
private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside world.
SingletonPatternDemo, our demo class will use SingleObject class to get a
SingleObject object.

Step 1
Create a Singleton Class.
SingleObject.java
public class SingleObject {

//create an object of SingleObject
private static SingleObject instance = new SingleObject();

//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}

//Get the only object available
public static SingleObject getInstance(){
return instance;
}

public void showMessage(){
System.out.println("Hello World!");
}
}
Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
public static void main(String[] args) {

//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();

//Get the only object available
SingleObject object = SingleObject.getInstance();

//show the message
object.showMessage();
}
}

3. FACTORY PATTERN
This type of design pattern comes under creational pattern as this pattern provides one
of the best ways to create an object. Factory Pattern is a design pattern to implement
the concept of factories.
In Factory pattern, we create object without exposing the creation logic to the client
and refer to newly created object using a common interface.
It is a design pattern to implement the concept of factories
This pattern is not a GoF pattern but a GoF Abstract Factory Pattern.This is also
called as simple or concrete factory.
Problem: Who would be responsible for creating objects when there are special
considerations such as complex creation logic, a desire to separate the creation
responsibilities for better cohesion.
Solution: Create a pure fabrication object called a factory that handles the creation.
Partial Data Driven Design: In service factory, the logic to decide which class to
create is resolved by reading the class name from an external resource and then
dynamically loading the class. This is termed as partial data driven design.
Advantages of Factory Objects:
o Separate the responsibility of complex creation into cohesive helper
objects.
o Hide potentially complex creation logic.
o Allow introduction of performance-enhancing memory management
strategies such as object caching or recycling.
Implementation
We're going to create a Shape interface and concrete classes implementing the Shape
interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It
will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get
the type of object it needs.

Step 1
Create an interface.
Shape.java
public interface Shape {
void draw();
}
Step 2
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {

@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {

@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {

@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory {

//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {

public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();

//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");

//call draw method of Circle
shape1.draw();

//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");

//call draw method of Rectangle
shape2.draw();

//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");

//call draw method of circle
shape3.draw();
}
}
Step 5
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

4. OBSERVER PATTERN
Defines a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically.
Observer Pattern is a software design pattern in which an object called the subject
maintains a list of its dependents called observers and notifies them automatically of
any state changes usually by calling one of their methods.
Problem: Different kinds of subscriber objects are interested in the state changes or
events of publisher objects and wants to react in their own unique way when the
publisher generates an event.Moreover,the publisher wants to maintain low coupling
to subscribers.
Solution: The publisher can dynamically register subscribers who are interested in an
event and notify them when an event occurs.
It is mainly used to implement distributed event handling system.
Why it is called Observer, Publish-Subscribe or Delegation Event Model?
o Objects that are interested, subscribe or register to interest in an event by
asking the publisher to notify them.
o When the event happens, the registered subscriber are notified by a message.
o It has been called Observer because the subscriber is observing the event.
o It has been called Delegation Event Model(in JAVA) because the publisher
delegates handling of events tolisteners

Advantages:
o Supports Low coupling from layers to the presentation (UI) layer of
objects.



A news agency gather news news and publish them to different subscribers. We need
to create a framework for and agency to be able to inform immediately, when event
occurs, its subscribers about the event. The subscribers can receive the news in
different ways: Emails, SMS, ...



The agency is represented by an Observable(Subject) class named NewsPublisher.
This one is created as an abstract class because the agency want to create several
types of Observable objects: in the beginning only for business news, but after some
time sport and political new will be published.
The concrete class is BusinessNewsPublisher.
The observer logic is implemented in NewsPublisher.
It keeps a list of all it subscribers and it informs them about the latest news. The
subscribers are represented by some observers (SMSSubscriber, EmailSubscriber).
Both the observers mentioned above are inherited from the Subscriber. The subscriber
is the abstract class which is known to the publisher.
The publisher doesn't know about concrete observers, it knows only about their
abstraction.
In the main class a publisher(Observable) is built and a few subscribers(Observers).
The subscribers are subscribed to the publisher and they can be unsubscribed.
In this architecture new types of subscribers can be easily added(instant messaging,
...) and new types of publishers(Weather News, Sport News, ...).

Anda mungkin juga menyukai