programming ii cs102cs102.coins-lab.org/lectures/designpatterns.pdf · builder pattern. structural...
TRANSCRIPT
DESIGN PATTERNS Anis Koubaa
PROGRAMMING II CS102
References
¨ Design Patterns in Java Tutorial ¨ http://www.tutorialspoint.com/design_pattern/
index.htm
¨ Design Patterns in Java ¨ http://www.javatpoint.com/design-patterns-in-
java
Design Patterns
¨ best practices used by experienced object-oriented software developers
¨ solutions to general problems that software developers faced during software development
¨ A design patterns are well-proved solution for solving the specific problem/task
¨ These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time
What is Gang of Four (GOF)?
¨ Gang of Four (GOF) ¤ Erich Gamma, ¤ Richard Helm, ¤ Ralph Johnson and ¤ John Vlissides
¨ In 1994, four authors published a book titled Design Patterns –
Elements of Reusable Object-Oriented Software
Principles of object orientated design
¨ According to these authors design patterns are primarily based on the following principles of object orientated design. ¤ Program to an interface not an implementation ¤ Favor object composition over inheritance
Usage of Design Pattern
¨ Design Patterns have two main usages in software development. ¤ Common platform for developers
n provide a standard terminology and are specific to particular scenario
¤ Best Practices n evolved over a long period of time n provide best solutions to certain problems faced
during software development.
Why Design Patterns?
¨ To become a professional software developer, you must know at least some popular solutions (i.e. design patterns) to the coding problems.
¨ By using the design patterns you can make your code more flexible, reusable and maintainable.
¨ It is the most important part because java internally follows design patterns.
When should we use the design patterns? ¨ We must use the design patterns during the
analysis and requirement phase of Software Development Life Cycle (SDLC).
¨ Design patterns ease the analysis and requirement phase of SDLC by providing information based on prior hands-on experiences.
Advantage of design pattern
¨ reusable in multiple projects. ¨ provide the solutions that help to define the
system architecture. ¨ capture the software engineering experiences. ¨ provide transparency to the design of an
application. ¨ are well-proved and testified solutions since they
have been built upon the knowledge and experience of expert software developers.
¨ don’t guarantee an absolute solution to a problem. ¤ provide clarity to the system architecture and the
possibility of building a better system.
Types of Design Patterns Three Categories ¨ Creational Patterns
¤ provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator.
¤ gives program more flexibility in deciding which objects need to be created for a given use case.
¨ Structural 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 ¤ These design patterns are specifically concerned with
communication between objects.
Types of Design Patterns One more Java-Specific Category
¨ 2EE Patterns ¤ specifically concerned with the presentation tier. ¤ identified by Sun Java Center.
• Creational Design Patterns • Structural Design Patterns • Behavioral Design Pattern
Core Java Design Patterns
Creational Design Pattern
¨ Factory Pattern ¨ Abstract Factory Pattern ¨ Singleton Pattern ¨ Prototype Pattern ¨ Builder Pattern.
Structural Design Pattern
¨ Adapter Pattern ¨ Bridge Pattern ¨ Composite Pattern ¨ Decorator Pattern ¨ Facade Pattern ¨ Flyweight Pattern ¨ Proxy Pattern.
Behavioral Design Pattern
¨ Chain Of Responsibility Pattern ¨ Command Pattern ¨ Interpreter Pattern ¨ Iterator Pattern ¨ Mediator Pattern ¨ Memento Pattern ¨ Observer Pattern ¨ State Pattern ¨ Strategy Pattern ¨ Template Pattern ¨ Visitor Pattern
Do You Know?
Creational Design Patterns
Creational design patterns
¨ Creational design patterns are concerned with the way of creating objects.
¨ used when a decision must be made at the time of instantiation of a class (i.e. creating an object of a class).
Creational design patterns
¨ Traditional Object Creation Student s1=new Student ();
¨ Hard-Coded code is not the good programming approach. ¤ 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.
Factory Pattern
Creational Design Patterns
Factory Pattern
¨ Factory 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.
¨ Factory pattern: create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Shape Interface Example
Step 1. Create an interface
public interface Shape { void draw();}
Shape.java
Step 2. Implement Classes
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Rectangle::draw() method.” );
}
}
Rectangle.java
Step 2. Implement Classes
public class Square implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Square::draw() method.” );
}
}
Square.java
Step 2. Implement Classes
public class Circle implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Circle::draw() method.” );
}
}
Circle.java
Step 3. Create A Factory Class 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; }} ShapeFactory.java
Step 4. Create Objects in Runtime
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(); }}
FactoryPatternDemo.java
Usage of Factory Design Pattern
¨ When a class doesn't know what sub-classes will be required to create
¨ When a class wants that its sub-classes specify the objects to be created.
¨ When the super classes choose the creation of objects to its sub-classes.
Singleton Pattern
Creational Design Patterns
Singleton Pattern
¨ Singleton pattern is one of the simplest design patterns in Java. ¤ it comes under creational pattern ¤ provides one of the best ways to create an object.
¨ This pattern involves a single class which is responsible to create an object while making sure that only single object gets 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.
Singleton Pattern
¨ Singleton Pattern says that just "define a class that has only one instance and provides a global point of access to it".
¨ In other words, a class must ensure that only single instance should be created and single object can be used by all other classes.
¨ There are two forms of singleton design pattern ¤ Early Instantiation: creation of instance at load time. ¤ Lazy Instantiation: creation of instance when
required.
Singleton Pattern vs. Static Class
¨ The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes), so you can pass around the singleton as if it were "just another" implementation.
¨ Performance: Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
¨ Ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.
http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern
http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
Advantage of Singleton Pattern
¨ Saves memory because object is not created at each request.
¨ Only single instance is reused again and again
Usage of Singleton design pattern
¨ Singleton pattern is mostly used in multi-threaded and database applications.
¨ It is used in logging, caching, thread pools, configuration settings etc.
How to create Singleton design pattern? ¨ To create the singleton class, we need to have
static member of class, private constructor and static factory method.
¨ Static member: It gets memory only once because of static, it contains the instance of the Singleton class.
¨ Private constructor: It will prevent to instantiate the Singleton class from outside the class.
¨ Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.
SingleObject Class
¨ Private Constructor ¨ Static instance of
itself ¨ provides a static
method to get its static instance to outside world
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!"); }}
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(); }}
Facade Pattern
Structural Design Patterns
Façade Pattern
¨ Facade pattern ¤ hides the complexities of the system and ¤ provides an interface to the client using which the
client can access the system. ¨ It is a structural pattern
¤ adds an interface to existing system to hide its complexities.
¨ This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.
Façade Pattern
¨ Facade pattern says that "just provide a unified and simplified interface to a set of interfaces in a subsystem, therefore it hides the complexities of the subsystem from the client".
¨ Facade Pattern describes a higher-level interface that makes the sub-system easier to use
Advantage of Facade Pattern
¨ It protects the clients from the complexities of the sub-system components.
¨ It promotes loose coupling between subsystems and its clients.
Usage of Facade Pattern
¨ When you want to provide simple interface to a complex sub-system.
¨ When several dependencies exist between clients and the implementation classes of an abstraction.
Façade Pattern Class Diagram
Step 1. Create an interface
public interface Shape { void draw();}
Shape.java
Step 2. Implement Classes
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Rectangle::draw() method.” );
}
}
Rectangle.java
Step 2. Implement Classes
public class Square implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Square::draw() method.” );
}
}
Square.java
Step 2. Implement Classes
public class Circle implements Shape {
@Override
public void draw() {
System.out.println(
”Inside Circle::draw() method.” );
}
}
Circle.java
Step 3. Create A Facade Class public class ShapeMaker {
private Shape circle; private Shape rectangle; private Shape square;
public ShapeMaker() { circle = new Circle(); rectangle = new Rectangle(); square = new Square(); }
public void drawCircle(){ circle.draw(); } public void drawRectangle(){ rectangle.draw(); } public void drawSquare(){ square.draw(); }} ShapeMaker.java
Step 4. Use Facade
public class FacadePatternDemo { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); }}
Model-View-Controller (MVC) Pattern
MVC Design Patterns
Model-View-Controller Pattern
¨ MVC Pattern stands for Model-View-Controller Pattern.
¨ separate application's calculations and interface from each other. ¤ Model - Model represents an object or JAVA POJO
carrying data. It can also have logic to update controller if its data changes.
¤ View - View represents the visualization of the data that model contains (The Interface).
¤ Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
Student MVC Class Diagram
Student MVC Class Diagram
¨ Model: Student class ¨ View: StudentView class will be a view class
which can print student details on console and ¨ Controller: StudentController is the controller
class responsible ¤ to store data in Student object and ¤ update view StudentView accordingly.
¨ MVCPatternDemo,: demo class, will use StudentController to demonstrate use of MVC pattern.
Step1. Model (Student.Java)
Step 2. View (StudentView.java)
Step 3. Controller (StudentController.java)
Step 4. Demo (MVCPatternDemo.java)
Step 5. Output