0% found this document useful (0 votes)
4 views22 pages

Struts Design Pattern

The document provides an overview of various design patterns in Java, including MVC architecture in Struts, Command, Adapter, Template, Composite, and Factory patterns. Each pattern is explained with its implementation steps, class diagrams, and example code. The document serves as a tutorial for understanding and applying these design patterns in software development.

Uploaded by

arnavsawant3006
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)
4 views22 pages

Struts Design Pattern

The document provides an overview of various design patterns in Java, including MVC architecture in Struts, Command, Adapter, Template, Composite, and Factory patterns. Each pattern is explained with its implementation steps, class diagrams, and example code. The document serves as a tutorial for understanding and applying these design patterns in software development.

Uploaded by

arnavsawant3006
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

Struts is based on model 2 MVC (Model-View-Controller) architecture.

Struts controller
uses the command design pattern and the action classes use the adapter design pattern.
The process() method of the RequestProcessor uses the template method design pattern.
Struts also implement the following J2EE design patterns.

Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token

Command Design
Pattern
This section describes command pattern and its
implementation.

C ommand pattern is a data driven design pattern and falls under behavioral pattern category. A request is
wrapped under 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 BuyStockand SellStockimplementing Orderinterface 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.
Class Diagram :
Steps
Use the following steps to implement the above mentioned design pattern.

Step 1
Create a command interface.
[Link]
public interface Order {
void execute();
}

Step 2
Create a request class.
[Link]
public class Stock {
private String name = "ABC";
privateint quantity = 10;

public void buy(){


[Link]("Stock [ Name: "+name+",
Quantity: " + quantity +" ] bought");
}
public void sell(){
[Link]("Stock [ Name: "+name+",
Quantity: " + quantity +" ] sold");
}
}

Step 3
Create concrete classes implementing the Order interface.
[Link]
public class BuyStock implements Order {
private Stock abcStock;
publicBuyStock(Stock abcStock){
[Link] = abcStock;
}
public void execute() {
[Link]();
}
}

[Link]
public class SellStock implements Order {
private Stock abcStock;
publicSellStock(Stock abcStock){
[Link] = abcStock;
}
public void execute() {
[Link]();
}
}

Step 4
Create command invoker class.
[Link]
[Link];
[Link];
public class Broker {
private List<Order>orderList = new ArrayList<Order>();
public void takeOrder(Order order){
[Link](order);
}
public void placeOrders(){
for (Order order : orderList) {
[Link]();
}
[Link]();
}
}

Step 5
Use the Broker class to take and execute commands.
[Link]
public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();
BuyStockbuyStockOrder = new BuyStock(abcStock);
SellStocksellStockOrder = new SellStock(abcStock);
Broker broker = new Broker();
[Link](buyStockOrder);
[Link](sellStockOrder);
[Link]();
}
}

Step 6
Verify the output.
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold

Adapter Design Pattern


This section describes adapter pattern and its
implementation.

A dapter 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 MediaPlayerinterface and a concrete class AudioPlayerimplementing
theMediaPlayerinterface. AudioPlayercan play mp3 format audio files by default.
We're having another interface AdvancedMediaPlayerand concrete classes implementing
[Link] classes can play vlc and mp4 format files.
We want to make AudioPlayerto play other formats as well. To attain this, we've created an adapter class
MediaAdapterwhich implements the MediaPlayerinterface and uses AdvancedMediaPlayerobjects to play the
required format.
AudioPlayeruses the adapter class MediaAdapterpassing it the desired audio type without knowing the actual
class which can play the desired format. AdapterPatternDemo, our demo class willuseAudioPlayerclass to play
various formats.
Class Diagram
Steps
Use the following steps to implement the above mentioned design pattern.

Step 1
Create interfaces for Media Player and Advanced Media Player.
[Link]
public interface MediaPlayer {
public void play(String audioType, String fileName);
}
[Link]
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}

Step 2
Create concrete classes implementing the AdvancedMediaPlayerinterface.
[Link]
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
[Link]("Playing vlc file. Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
//do nothing
}
}
[Link]
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
[Link]("Playing mp4 file. Name: "+ fileName);
}
}

Step 3
Create adapter class implementing the MediaPlayerinterface.
[Link]
public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayeradvancedMusicPlayer;
publicMediaAdapter(String audioType){
if([Link]("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if ([Link]("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if([Link]("vlc")){
[Link](fileName);
}else if([Link]("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}

Step 4
Create concrete class implementing the MediaPlayerinterface.
[Link]
public class AudioPlayer implements MediaPlayer {
MediaAdaptermediaAdapter;
@Override
public void play(String audioType, String fileName) {
//inbuilt support to play mp3 music files
if([Link]("mp3")){
[Link]("Playing mp3 file. Name: "+ fileName);
}
//mediaAdapter is providing support to play other file formats
else if([Link]("vlc")
|| [Link]("mp4")){
mediaAdapter = new MediaAdapter(audioType);
[Link](audioType, fileName);
}
else{
[Link]("Invalid media. "+
audioType + " format not supported");
}
}}
Step 5
Use the AudioPlayer to play different types of audio formats.
[Link]
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayeraudioPlayer = new AudioPlayer();
[Link]("mp3", "beyond the horizon.mp3");
[Link]("mp4", "alone.mp4");
[Link]("vlc", "far [Link]");
[Link]("avi", "mind [Link]");
}
}

Step 6
Verify the output.
Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far [Link]
Invalid [Link] format not supported

TemplateDesign
Pattern
This section describes templatepattern and its
implementation.

I n 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.
Class Diagram
Steps
Use the following steps to implement the above mentioned design pattern.

Step 1
Create an abstract class with a template method being final.
[Link]
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//template method
public final void play(){
//initialize the game
initialize();
//start game
startPlay();
//end game
endPlay();
}
}

Step 2
Create concrete classes extending the above class.
[Link]
public class Cricket extends Game {
@Override
voidendPlay() {
[Link]("Cricket Game Finished!");
}
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}
@Override
voidstartPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}
}
[Link]
public class Football extends Game { TUTORIALS POINT Simply Easy
Learning Page 115
@Override
voidendPlay() {
[Link]("Football Game Finished!");
}
@Override
void initialize() {
[Link]("Football Game Initialized! Start playing.");
}
@Override
voidstartPlay() {
[Link]("Football Game Started. Enjoy the game!");
}
}

Step 3
Use the Game's template method play() to demonstrate a defined way of playing game.
[Link]
public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
[Link]();
[Link]();
game = new Football();
[Link]();
}
}

Step 4
Verify the output.
Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!
Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!

CHAPTER

C omposite 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
hierarchies. 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.

CHAPTER

10 TUTORIALS POINT Simply Easy Learning Page 46


Class Diagram TUTORIALS POINT Simply Easy Learning Page 47
Steps
Use the following steps to implement the above mentioned design pattern.

Step 1
Create Employee class having list of Employee objects.
[Link]
import [Link];
import [Link];
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
// constructor
public Employee(String name,String dept, int sal) {
[Link] = name;
[Link] = dept;
[Link] = salary;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
[Link](e);
}
public void remove(Employee e) {
[Link](e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("Employee :[ Name : "+ name
+", dept : "+ dept + ", salary :"
+ salary+" ]");
}
}

Step 2
Use the Employee class to create and print employee hierarchy.
[Link]
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000); TUTORIALS POINT Simply
Easy Learning Page 48
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
[Link](headSales);
[Link](headMarketing);
[Link](salesExecutive1);
[Link](salesExecutive2);
[Link](clerk1);
[Link](clerk2);
//print all employees of the organization
[Link](CEO);
for (Employee headEmployee : [Link]()) {
[Link](headEmployee);
for (Employee employee : [Link]()) {
[Link](employee);
}
}
}
}

Step 3
Verify the output.
Employee :[ Name : John, dept : CEO, salary :30000 ]
Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
Employee :[ Name : Richard, dept : Sales, salary :10000 ]
Employee :[ Name : Rob, dept : Sales, salary :10000 ]
Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
Employee :[ Name : Bob, dept : Marketing, salary :10000 ]

Factory Pattern
This section describes factory pattern and its
implementation.

F actory pattern is one of most used design pattern 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 Shape object. It will pass information
(CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.

Class Diagram TUTORIALS POINT Simply Easy Learning Page 4


Steps
Use the following steps to implement the above mentioned design pattern.

Step 1
Create an interface.
[Link]
public interface Shape {
void draw();
}

Step 2
Create concrete classes implementing the same interface.
[Link]
public class Rectangle implements Shape {
@Override
public void draw() {
[Link]("Inside Rectangle::draw() method.");
}
}
[Link]
public class Square implements Shape {
@Override
public void draw() {
[Link]("Inside Square::draw() method.");
}
}
[Link]
public class Circle implements Shape {
@Override
public void draw() {
[Link]("Inside Circle::draw() method.");
}
} TUTORIALS POINT Simply Easy Learning Page 5
Step 3
Create a Factory to generate object of concrete class based on given information.
[Link]
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if([Link]("CIRCLE")){
return new Circle();
} else if([Link]("RECTANGLE")){
return new Rectangle();
} else if([Link]("SQUARE")){
return new Square();
}
return null;
}
}

Step 4
Use the Factory to get object of concrete class by passing an information such as type.
[Link]
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 = [Link]("CIRCLE");
//call draw method of Circle
[Link]();
//get an object of Rectangle and call its draw method.
Shape shape2 = [Link]("RECTANGLE");
//call draw method of Rectangle
[Link]();
//get an object of Square and call its draw method.
Shape shape3 = [Link]("SQUARE");
//call draw method of circle
[Link]();
}
} TUTORIALS POINT Simply Easy Learning Page 6
Step 5
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

You might also like