0% found this document useful (0 votes)
139 views20 pages

Factory Pattern: Types of Design Pattern

The document discusses various design patterns categorized as creational, structural, behavioral, and J2EE patterns. It provides examples of implementing the Factory, Abstract Factory, Singleton, Builder, Prototype, Adapter, Bridge, Filter/Criteria, and Composite patterns. Each pattern example includes interfaces, classes, and a demo class to showcase the pattern's usage and flexibility in solving common programming problems.

Uploaded by

Amit Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views20 pages

Factory Pattern: Types of Design Pattern

The document discusses various design patterns categorized as creational, structural, behavioral, and J2EE patterns. It provides examples of implementing the Factory, Abstract Factory, Singleton, Builder, Prototype, Adapter, Bridge, Filter/Criteria, and Composite patterns. Each pattern example includes interfaces, classes, and a demo class to showcase the pattern's usage and flexibility in solving common programming problems.

Uploaded by

Amit Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Types of Design Pattern

As per the design pattern reference book Design Patterns - Elements of Reusable Object-Oriented

Software , there are 23 design patterns. These patterns can be classified in three categories: Creational, Structural
and behavioral patterns. We'll also discuss another category of design patterns: J2EE design patterns.

S.N. Pattern & Description

Creational Patterns
These design patterns provides way to create objects while hiding the creation logic, rather than
1
instantiating objects directly using new operator. This gives program more flexibility in deciding which
objects need to be created for a given use case.

Structural Patterns
2 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.

Behavioral Patterns
3
These design patterns are specifically concerned with communication between objects.

J2EE Patterns
4 These design patterns are specifically concerned with the presentation tier. These patterns are
identified by Sun Java Center.

Factory Pattern
Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational
pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created
object using a common interface.

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 Shapeobject. It will pass information (CIRCLE
/ RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.
Design Pattern - Abstract Factory Pattern
Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as

factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the
best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly
specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Implementation
We are going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We create

an abstract factory class AbstractFactory as next step. Factory classes ShapeFactory and ColorFactoryare defined
where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.

AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass

information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs. It
also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.

Singleton Pattern
Singleton pattern is one of the simplest design patterns in Java. 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.

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.

Builder Pattern
Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design
pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

A Builder class builds the final object step by step. This builder is independent of other objects.

Implementation
We've considered a business case of fast-food restaurant where a typical meal could be a burger and a cold drink.

Burger could be either a Veg Burger or Chicken Burger and will be packed by a wrapper. Cold drink could be either
a coke or pepsi and will be packed in a bottle.

We're going to create an Item interface representing food items such as burgers and cold drinks and concrete

classes implementing the Item interface and a Packing interface representing packaging of food items and concrete
classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed
as bottle.

We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal object by
combining Item. BuilderPatternDemo, our demo class will use MealBuilder to build a Meal.
Prototype Pattern
Prototype pattern refers to creating duplicate object while keeping performance in mind. 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 implementing a prototype interface which tells to create a clone of the current object. This

pattern is used when creation of object directly is costly. For example, a object is to be created after a costly

database operation. We can cache the object, returns its clone on next request and update the database as as and
when needed thus reducing database calls.

Implementation
We're going to create an abstract class Shape and concrete classes extending the Shape class. A

class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when
requested.

PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.
Adapter Pattern
Adapter pattern works as a bridge between two incompatible interfaces. 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. 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.

Implementation
We've an interface MediaPlayer interface and a concrete class AudioPlayerimplementing
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.
Bridge Pattern
Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary

independently. This type of design pattern comes under structural pattern as this pattern decouples implementation
class and abstract class by providing a bridge structure between them.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes

independent from interface implementer classes. Both types of classes can be altered structurally without affecting
each other.

We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors
using same abstract class method but different bridge implementer classes.

Implementation
We've an interface DrawAPI interface which is acting as a bridge implementer and concrete

classes RedCircle, GreenCircle implementing the DrawAPIinterface. Shape is an abstract class and will use object
of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle.
Filter/Criteria Pattern
Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects, using different

criteria, chaining them in a decoupled way through logical operations. This type of design pattern comes under
structural pattern as this pattern is combining multiple criteria to obtain single criteria.

Implementation
We're going to create a Person object, Criteria interface and concrete classes implementing this interface to filter

list of Person objects. CriteriaPatternDemo, our demo class uses Criteria objects to filter List of Person objects
based on various criteria and their combinations.

Composite Pattern
Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite

pattern composes objects in term of a tree structure to represent part as well as whole hierarchy . This type of
design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.

This pattern creates a class contains group of its own objects. This class provides ways to modify its group of same
objects.

We are demonstrating use of Composite pattern via following example in which show employees hierarchy of an
organization.

Implementation
We've a class Employee which acts as composite pattern actor class. CompositePatternDemo, our demo class will
use Employee class to add department level hierarchy and print all employees.

Decorator Pattern
Decorator pattern allows to add new functionality an existing object without altering its structure. This type of
design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.

This pattern creates a decorator class which wraps the original class and provides additional functionality keeping
class methods signature intact.

We are demonstrating use of Decorator pattern via following example in which we'll decorate a shape with some
color without alter shape class.

Implementation
We're going to create a Shape interface and concrete classes implementing the Shape interface. We then create a
abstract decorator class ShapeDecorator implementing the Shape interface and having Shape object as its instance
variable.

RedShapeDecorator is concrete class implementing ShapeDecorator.


DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects.

Facade Pattern
Facade pattern hides the complexities of the system and provides an interface to the client using which the client

can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface
to exiting system to hide its complexities.

This pattern involves a single class which provides simplified methods which are required by client and delegates
calls to existing system classes methods.

Implementation
We're going to create a Shape interface and concrete classes implementing the Shape interface. A facade
class ShapeMaker is defined as a next step.

ShapeMaker class uses the concrete classes to delegates user calls to these classes. FacadePatternDemo, our demo
class will use ShapeMaker class to show the results.
Flyweight Pattern
Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and

increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to
decrease objects count thus improving application required objects structure.

Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when

no matching object is found. We'll demonstrate this pattern by drawing 20 circle of different locations but we'll
creating only 5 objects. Only 5 colors are available so color property is used to check already existing Circle objects.

Implementation
We're going to create a Shape interface and concrete class Circleimplementing the Shape interface. A factory
class ShapeFactory is defined as a next step.

ShapeFactory have a HashMap of Circle having key as color of the Circleobject. Whenever a request comes to
create a circle of particular color to ShapeFactory. ShapeFactory checks the circle object in its HashMap, if object

of Circle found, that object is returned otherwise a new object is created, stored in hashmap for future use and
returned to client.

FlyWeightPatternDemo, our demo class will use ShapeFactory to get a Shapeobject. It will pass information (red /
green / blue/ black / white) to ShapeFactory to get the circle of desired color it needs.
Proxy Pattern
In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under
structural pattern.

In Proxy pattern, we create object having original object to interface its functionality to outer world.

Implementation
We're going to create a Image interface and concrete classes implementing the Image interface. ProxyImage is a
a proxy class to reduce memory footprint of RealImage object loading.

ProxyPatternDemo, our demo class will use ProxyImage to get a Image object to load and display as it needs.

Chain of Responsibility Pattern


As the name suggest, the chain of responsibility pattern creates a chain of receiver objects for a request. This

pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral
patterns.
In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the
request then it passes the same to the next receiver and so on.

Implementation
We've created an abstract class AbstractLogger with a level of logging. Then we've created three types of loggers

extending the AbstractLogger. Each logger checks the level of message to its level and print accordingly otherwise
does not print and pass the message to its next logger.

Command Pattern
Command pattern is a data driven design pattern and falls under behavioral pattern category. A request is wrapped

under a object as command and passed to invoker object. Invoker object looks for the appropriate object which
can handle this command and pass the command to the corresponding object and that object executes the
command.

Implementation
We've created an interface Order which is acting as a command. We've created a Stock class which acts as a

request. We've concrete command classes BuyStock and SellStock implementing Order interface which will do

actual command processing. A class Broker is created which acts as a invoker object. It can take order and place
orders.

Broker object uses command pattern to identify which object will execute which command based on type of
command. CommandPatternDemo, our demo class will use Broker class to demonstrate command pattern.
Interpreter Pattern
Interpreter pattern provides way to evaluate language grammar or expression. This type of pattern comes under

behavioral patterns. This pattern involves implementing a expression interface which tells to interpret a particular
context. This pattern is used in SQL parsing, symbol processing engine etc.

Implementation
We're going to create an interface Expression and concrete classes implementing the Expression interface. A

class TerminalExpression is defined which acts as a main interpreter of context in question. Other
classes OrExpression, AndExpression are used to create combinational expressions.

InterpreterPatternDemo, our demo class will use Expression class to create rules and demonstrate parsing of
expressions.
Iterator Pattern
Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is

used to get a way to access the elements of a collection object in sequential manner without any need to know its
underlying representation.

Iterator pattern falls under behavioral pattern category.

Implementation
We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns

the iterator . Concrete classes implementing the Container interface will be responsible to
implement Iteratorinterface and use it

IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print
a Names stored as a collection in NamesRepository.
Mediator Pattern
Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern

provides a mediator class which normally handles all the communications between different classes and supports
easy maintainability of the code by loose coupling. Mediator pattern falls under behavioral pattern category.

Implementation
We're demonstrating mediator pattern by example of a Chat Room where multiple users can send message to Chat

Room and it is the responsibility of Chat Room to show the messages to all users. We've created two
classes ChatRoom and User. User objects will use ChatRoom method to share their messages.

MediatorPatternDemo, our demo class will use User objects to show communication between them.

Memento Pattern
Memento pattern is used to reduce where we want to restore state of an object to a previous state. Memento
pattern falls under behavioral pattern category.

Implementation
Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates

and stores states in Memento objects and Caretaker object which is responsible to restore object state from
Memento. We've created classes Memento, Originator and CareTaker.

MementoPatternDemo, our demo class will use CareTaker and Originatorobjects to show restoration of object
states.
Observer Pattern
Observer pattern is used when there is one to many relationship between objects such as if one object is modified,
its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Implementation
Observer pattern uses three actor classes. Subject, Observer and Client. Subject, an object having methods to

attach and de-attach observers to a client object. We've created classes Subject, Observer abstract class and
concrete classes extending the abstract class the Observer.

ObserverPatternDemo, our demo class will use Subject and concrete class objects to show observer pattern in
action.
State Pattern
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior
pattern.

In State pattern, we create objects which represent various states and a context object whose behavior varies as
its state object changes.

Implementation
We're going to create a State interface defining a action and concrete state classes implementing
the State interface. Context is a class which carries a State.

StaePatternDemo, our demo class will use Context and state objects to demonstrate change in Context behavior
based on type of state it is in.

Null Object Pattern


In Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null

value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour
in case data is not available.

In Null Object pattern, we create a abstract class specifying the various operations to be done, concreate classes

extending this class and a null object class providing do nothing implemention of this class and will be used
seemlessly where we need to check null value.

Implementation
We're going to create a AbstractCustomer abstract class defining opearations, here the name of the customer and

concrete classes extending the AbstractCustomer class. A factory class CustomerFactory is created to return
either RealCustomer or NullCustomer objects based on the name of customer passed to it.

NullPatternDemo, our demo class will use CustomerFactory to demonstrate use of Null Object pattern.

Strategy Pattern
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes
under behavior pattern.

In Strategy pattern, we create objects which represent various strategies and a context object whose behavior
varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

Implementation
We're going to create a Strategy interface defining a action and concrete strategy classes implementing
the Strategy interface. Context is a class which uses a Strategy.

StrategyPatternDemo, our demo class will use Context and strategy objects to demonstrate change in Context
behaviour based on strategy it deploys or uses.
Template Pattern
In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses

can overrides the method implementations as per need basis but the invocation is to be in the same way as defined
by an abstract class. This pattern comes under behavior pattern category.

Implementation
We're going to create a Game abstract class defining operations with a template method set to be final so that it
cannot be overridden. Cricket and Football are concrete classes extend Game and override its methods.

TemplatePatternDemo, our demo class will use Game to demonstrate use of template pattern.
Visitor Pattern
In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. By this way,

execution algorithm of element can varies as visitor varies. This pattern comes under behavior pattern category.

As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on
the element object.

Implementation
We're going to create a ComputerPart interface defining accept

opearation.Keyboard, Mouse, Monitor and Computer are concrete classes implementing ComputerPart interface.

We'll define another interface ComputerPartVisitor which will define a visitor class operations. Computeruses
concrete visitor to do corresponding action.

VisitorPatternDemo, our demo class will use Computer, ComputerPartVisitorclasses to demonstrate use of visitor
pattern.

You might also like