SlideShare a Scribd company logo
DP = scalable app = save time
Anas alpure
design patterns
Creational Patterns:
Structural Patterns:
Behavioral Patterns:
• Singleton Pattern
• Abstract Factory Pattern
• Prototype Pattern
• Factory Method Pattern
• Builder Pattern
• Proxy Pattern
• Flyweight Pattern
• Bridge Pattern
• Facade Pattern
• Decorator Pattern
• Adapter Pattern
• Composite Pattern
• Observer Pattern
• Template Method Pattern
• Command Pattern
• Iterator Pattern
• State Pattern
• Mediator Pattern
• Strategy Pattern
• Chain of Responsibility Pattern
• Visitor Pattern
• Interpreter Pattern
• Memento Pattern
design patterns
DP = scalable app = save time
naming conventions in java
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
Java Package
Singleton Patterns
A particular class should have only one instance.
we have made the constructor private
so that we cannot instantiate in normal fashion.
When we attempt to create an instance of the class,
we are checking whether we already have one available copy.
If we do not have any such copy, we’ll create it;
otherwise, we’ll simply reuse the existing copy.
getInstance
GoF Definition: Ensure a class only has one instance, and provide a global point of access to it.
Flyweight Pattern
GoF Definition: Use sharing to support large numbers of fine-grained objects efficiently.
we try to minimize memory usage by sharing data as much as possible.
Map<String, IRobot> shapes = new HashMap<String, IRobot>();
getInstance(String str) {
if (shapes.containsKey(str)){
}
else
{
switch (str){
}
}
}
Prototype Pattern(cloning)
GoF Definition: Specify the kinds of objects to create using a prototypical instance,
and create new objects by copying this prototype.
- prototype pattern provides an alternative method for instantiating new objects by copying or cloning an instance of an existing one.
Builder Pattern
0..10..1
0..1
The Director class constructs the complex object using the Builder interface.
parts
class Car implements IBuilder
{
private Product product = new Product();
@Override
public void BuildBody()
{ product.Add("This is a body of a Car") ; }
@Override
public void InsertWheels()
{ product.Add("4 wheels are added"); }
@Override
public void AddHeadlights()
{ product.Add…... }
@Override
public Product GetVehicle()
{ return product; }
}
class Director
{
IBuilder myBuilder;
public void Construct(IBuilder builder)
{
myBuilder=builder;
myBuilder.BuildBody();
myBuilder.InsertWheels();
myBuilder.AddHeadlights();
}
}
// main method
IBuilder carBuilder = new Car();
// Making Car
director.Construct(carBuilder);
Product p1 = carBuilder.GetVehicle();
p1.Show();
GoF Definition: Separate the construction of a complex object from its representation
parts
Observer Patterns
GoF Definition: Define a one-to-many dependency between objects so that when one object (subject) changes state,
all its dependents(observers) are notified and updated automatically.
UML Class Diagram
Push and Pull
• Push algorithm:
When the Subject (Publisher) updates the Observers (Subscribers), it sends the data
to all of them even if they don’t need it, so it is a negative aspect of the algorithm.
• Pull algorithm:
When the Subject (Publisher) updates the Observers (Subscribers), it only tells them
that the data is changed, so Observers (Subscribers) retrieve it if they need the data.
• Pull algorithm is better.
Factory Method Pattern
Factory pattern, we create object without exposing the creation logic to
the client and refer to newly created object using a common interface. Factory
Pattern
"I want red car"
‫المبدء‬‫لـ‬ ‫األول‬SOLID‫مبدء‬‫المسؤلية‬‫الوحيدة‬
GoF Definition: Define an interface for creating an object, but let subclasses decide which class to
instantiate. The factory method lets a class defer instantiation to subclasses.
is also known as Virtual Constructor.
Abstract Factory Patterns(super-factory )
abstract Factory patterns work around a super-factory which creates other factories.
This factory is also called as factory of factories
Provides an interface or abstract class
for creating families of related (or dependent) objects
but without specifying their concrete sub-classes.
That means Abstract Factory lets
a class returns a factory of classes.
So, this is the reason that Abstract Factory Pattern is
one level higher than the Factory Pattern.
is also known as Kit.
0..1
Proxy PatternsGoF Definition: Provide a surrogate or placeholder for another object to control access to it.
‫نائب‬
A proxy is an object that can be used to control access to another object.
Adapter Patterns
GoF Definition: Convert the interface of a class into another interface that clients expect.
Adapter pattern works as a bridge between two incompatible interfaces.
- Wrap an existing class with a new interface.
<<Class>>
FacebookApi
Do_post(msg)
Get_post()
<<interface>>
SocialMedia
post(msg)
getPost()
<<Class>>
facebookAdapter
+facebookApi
post(msg)
getPost()
Adaptee
Adaptor
0..1
Template Method Patterns / abstract
GoF Definition: Define the skeleton of an algorithm in an operation,
deferring some steps to subclasses.
The template method lets subclasses redefine certain steps of an algorithm
without changing the algorithm’s structure.
0..1
We can select the behavior of
an algorithm dynamically at runtime.
‫يحقق‬‫مبدء‬OCP
Strategy Patterns (Or, Policy Patterns) /Context
1 class to many behaviors
1 context to family of behaviors
[1:many relationship]
context
‫بها‬ ‫خاص‬ ‫وسلوك‬ ‫متلف‬ ‫بشكل‬ ‫تعرض‬ ‫بطة‬ ‫كل‬.
enables selecting an algorithm at runtime. The strategy pattern
-defines a family of algorithms,
-encapsulates each algorithm, and
-makes the algorithms interchangeable within that family.
Strategy lets the algorithm vary independently from clients that use it.
Decorator Patterns
You would use it when you
want the capabilities of
inheritance with
subclasses, but you need
to add functionalities at
run time.
attach a flexible additional responsibilities
to an object dynamically"
Decorator Patterns Interface i = new O1(new O2(new O3())); Component
AbstractDecorator base Component
ConcreteEX1 ConcreteEX2
0..1
‫المجرد‬ ‫الكلس‬ ‫يمتلك‬AbstractDecorator‫الوكيل‬ ‫دور‬
‫من‬ ‫مقبض‬ ‫يمتلك‬ ‫حيث‬Component‫المقبض‬ ‫هذا‬
‫األنواع‬ ‫من‬ ‫أي‬ ‫الى‬ ‫يشير‬ ‫ان‬ ‫يمكن‬‫الثالئة‬‫ال‬EX1,EX2,base..
‫تنفيذ‬ ‫عند‬EX2.doJob()
‫لدالة‬ ‫التنفيذ‬ ‫فان‬doJob‫في‬ ‫الموجودة‬EX2
‫التالية‬ ‫التعليمة‬ ‫تحوي‬ ‫والتي‬super.doJob();
‫الـ‬super‫ل‬EX2‫هو‬AbstractDecorator
‫في‬ ‫يحوي‬ ‫والذي‬doJob‫به‬ ‫الخاصة‬
‫الوصول‬ ‫حتا‬ ‫االمر‬ ‫يتكرر‬ ‫وهكذا‬‫لل‬base
‫تحوي‬ ‫ال‬ ‫التي‬ ‫و‬super.doJob();‫دالة‬ ‫في‬doJob‫اب‬ ‫لديها‬ ‫ليس‬ ‫الن‬(interface)
‫ملف‬ ‫في‬ ‫موجود‬ ‫الكود‬decorator anas.java
Decorator‫من‬ ‫خاصة‬ ‫حالة‬Composite(‫شجري‬ ‫تمثيل‬tree)
abstract class Component {
public abstract void doJob();
}
//base calss
class ConcreteComponent extends Component {
@Override
public void doJob() {
System.out.println(" this base job");
}
}
//Decorator
abstract class AbstractDecorator extends Component {
protected Component com;
public AbstractDecorator(Component c) {
com = c;
}
public void doJob() {
if (com != null) {
com.doJob();
}
}
}
//extra class1
class ConcreteDecoratorEx_1 extends AbstractDecorator {
public ConcreteDecoratorEx_1(Component c) {
super(c);
}
public void doJob() {
System.out.println("** Ex-1 START**");
super.doJob();
System.out.println("** EX-1 end**");
}
}
Decorator Patterns
Attach additional responsibilities to an object dynamically.
add behavior or state to individual objects at run-time.
Inheritance is not feasible because it is static and applies to an entire class.
interface AbstractFile {
void ls();
}
class Directory implements AbstractFile {
private String name;
private ArrayList includedFiles=new ArrayList();
public Directory(String name) {
this.name = name;
}
public void add(Object obj) {
includedFiles.add(obj);
}
public void ls() {
System.out.println(name);
for (Object includedFile : includedFiles) { }
}
}
Composite Patterns
we make a composite object when we have many objects with common functionalities.
This relationship is also termed a “has-a” relationship among objects.
Any tree structure in computer science can follow a similar concept.
0 ..*
Directory
Name:String
List< AbstractFile >
Add()
Remove()
getDetails()
AbstractFile
getDetails()
file
getDetails()
GoF Definition: Compose objects into tree structures to represent part-whole hierarchies.
The composite pattern lets clients treat individual objects and compositions of objects uniformly.
Command Patterns is also known as Action
0..1
‫الغرض‬ ‫لدينا‬Receiver‫مهام‬ ‫عدة‬ ‫بإنجاز‬ ‫يقوم‬
‫الغرض‬ ‫ولدينا‬Invoke‫السابقة‬ ‫المهام‬ ‫ينفذ‬ ‫ان‬ ‫يريد‬
‫الطالب‬ ‫لفصل‬Invoke‫المطلوب‬ ‫عن‬Receiver‫النموذج‬ ‫هذا‬ ‫يقترح‬:
‫في‬ ‫مهمة‬ ‫لكل‬ ‫كلس‬ ‫انشاء‬Receiver‫من‬ ‫ترث‬Icommand
‫و‬Invoke‫تستقبل‬ ‫دالة‬ ‫يحقق‬‫بارمتر‬Icommand
‫يمكن‬ ‫وبالتالي‬‫لل‬‫ـ‬Invokeً‫ال‬‫مث‬ ‫عنها‬ ‫والتراجع‬ ‫تنفيذها‬ ‫تم‬ ‫التي‬ ‫األخيرة‬ ‫المهام‬ ‫معرفة‬.....
RemoteControl
//Invoker
public class RemoteControl{
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void pressButton(){
command.execute();
}
}
//Receiver
public class Light{
private boolean on;
public void switchOn(){
on = true;
}
public void switchOff(){
on = false;
}
} RemoteControl control = new RemoteControl();
Light light = new Light();
Command lightsOn = new LightsOnCommand(light);
Command lightsOff = new LightsOffCommand(light);
//switch on
control.setCommand(lightsOn);
control.pressButton();
//Concrete Command
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light){
this.light = light;
}
public void execute(){
light.switchOn();
}
}
Client
Command Patterns is also known as Action
GoF Definition: Encapsulate a request as an object,
and pass it to invoker object.
•It separates the object that invokes the operation from the object that actually performs the operation.
•It makes easy to add new commands,
‫يستخدم‬Command‫حيث‬ ‫مهام‬ ‫عدة‬ ‫لتنفيذ‬‫في‬ ‫مهمة‬ ‫كل‬ ‫يغلف‬object‫عن‬ ‫تراجع‬ ‫عمل‬ ‫يمكن‬ ‫وأيضا‬ ‫به‬ ‫نفذت‬ ‫التي‬ ‫بالترتيب‬ ‫يحفظها‬ ‫و‬Undo‫و‬Redo
<<interface>>
ICommand
+execute()
+undo()
//redo
0 ..*
push( Icommand c ){
c. execute();
redoStack.clear();
undoStack.push(c);
}
CommandStack‫عن‬ ‫مسؤول‬
‫الـ‬ ‫إدارة‬commands‫ونقلها‬
‫المكدسات‬ ‫بين‬
<<Class>>
CommansStack
+execute()
+undo()
+push(Icommand c)
- undoStack <<Icommand>>
- redoStack <<Icommand>>
Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
Problem
Memento Pattern
provides the ability to restore an object to its previous state (undo via rollback).
The memento pattern is implemented with three objects:
• the originator ,
• a caretaker ,
• a memento .
- Our aim is to save the state of an object(originator),
so that in the future, we can go back to the specified state.
- the memento pattern operates on a single object.
0..1 0..1
class Originator
{
private String state;
Memento m;
public void setState(String state)
{
this.state = state;
}
// Creates memento
public Memento OriginatorMemento()
{
m = new Memento(state);
return m;
}
public void Revert(Memento memento)
{
state = memento.getState();
}
}
Design patterns
Visitor Pattern / APIs
This pattern helps us to add new functionalities to an existing object structure in such a way
that the old structure remains unaffected by these changes. So,
we can follow the open/close principle here :
(extension allowed but modification disallowed for entities like class, function, modules, etc.).
‫ممنوع‬ ‫التعديل‬ ‫و‬ ‫مسموحة‬ ‫اإلضافة‬
Plugging into public APIs is a common example.
Then a client can perform his desired operations
without modifying the actual code (with a visiting class).
many classes to many behaviors[many:many relationship]
Visitor lets you define a new operation without changing the classes
API
<<interface>>
Iitem
+getDiscount(DiscountPolicy d)
+get_price()
<<Class>>
Book
+getDiscount()
+get_price()
<<Class>>
Pen
+getDiscount()
+get_price()
<<interface>>
IDiscountPolicy
+getDiscount(Book b)
+getDiscount(Pen p)
<< Class >>
DiscountPolicy
+getDiscount(Book b)
+getDiscount(Pen p)
IVisitor
@Override
public float getDiscount (DiscountPolicy d)
{
return d. getDiscount(this);
}
Overloading
0..1
API
Strategy patternvisitor pattern
‫تركيب‬ ‫عالقة‬
‫اعتمادية‬ ‫عالقة‬
1 class to many behaviors
[1:many relationship]
many classes to many behaviors
[many:many relationship]
We can select the behavior of an algorithm dynamically at runtimeadd new functionalities to an existing
object structure
‫مثل‬ ‫جديد‬ ‫كلس‬ ‫إضافة‬ ‫عند‬MyClass2
‫نضيف‬ ‫فقط‬override function visit(MyClass2)
‫في‬Visitor class
‫التنفيذ‬ ‫اثناء‬ ‫للتغير‬ ‫قابل‬(dynamically)
‫فقط‬ ‫جديد‬ ‫سلوك‬ ‫إضافة‬ ‫يمكن‬
State Patterns
0..1
ON OFF
ON OFF
GoF Definition: Allow an object to alter its behavior
when its internal state changes.
The object will appear to change its class.
Iterator Pattern
Provide a way to access the elements of an aggregate object sequentially.
it doesn’t care which data structure is used .
‫أي‬aggregate object‫محتواه‬ ‫يعيد‬ ‫ان‬ ‫يريد‬
‫عبر‬Iterator‫الوجهة‬ ‫يطبق‬Iaggregate
‫الطريقة‬ ‫تعريف‬ ‫ويعيد‬CreateIterator()
‫نوع‬ ‫من‬ ‫كائن‬ ‫تعيد‬ ‫التي‬Iterator
‫الدوال‬ ‫تعريف‬ ‫ويعيد‬ ‫ببرمجته‬ ‫يقوم‬"First,Next,…."
we Can combine the iterator pattern with the composite pattern
Need to "abstract" the traversal of wildly different data structures
Problem
Mediator Pattern
GoF Definition: Define an object that encapsulates how a set of objects interacts.
The advantage of using such a mediator is that we can
reduce the direct interconnections among the objects and
thus lower the coupling.
“ many-to-many” relationship ”
ChatRoom
Colleague
0..*
<<abstract>>
sendMessage(message, sender)
‫الكل‬ ‫الى‬ ‫رسالة‬ ‫ارسال‬ ‫يستطيع‬ ‫عضو‬ ‫كل‬many-to-many=>Mediator
‫ارسال‬ ‫يستطيع‬ ‫عضو‬‫رسالى‬‫للكل‬one-to-many=>Observer
DesktopColleague MobileColleague
Imediator
many-to-many
• ColleagueBase: this is the abstract class (or interface) for all concrete colleagues. It has a protected field that holds a reference to the mediator object.
• ConcreteColleague: this is the implementation of the ColleagueBase class. Concrete colleagues are classes which communicate with each other.
• MediatorBase: this is the abstract class for the mediator object. This class contains methods that can be consumed by colleagues.
• ConcreateMediator: this class implements communication methods of the MediatorBase class.
This class holds a reference to all colleagues which need to communicate.
The Model View Controller ( MVC ) : a Composed Pattern.
Model:
- Contains data.
- Encapsulates application state.
- Responds to state queries/updates.
- Exposes application functionality.
View:
- Renders the model.
- Allows Controller to select view.
- Sends user input to the Controller.
Controller:
- Defines application behavior.
- Maps user actions to Model updates.
Structure Pattern
OOP Principles SOLIDsingle responsibility principle : A class should have only one reason to chang (factory)
The Open-Closed Principle: Software Entities Should Be Open For Extension, Yet Closed For Modification
( Visitor – Strategy )
The Single Choice Principle: (Singleton)
The Liskov Substitution Principle(LSP) ” ‫استبدال‬‫لسكوف‬ ”:
Functions That Use References To Base (Super) Classes Must Be
Able To Use Objects Of Derived(Sub) Classes Without Knowing It
If a function does not satisfy the LSP, then it probably makes explicit reference
to some or all of the subclasses of its superclass.
Such a function also violates the Open-Closed Principle,
since it may have to be modified whenever a new subclass is created.
A subtype must have no more constraints than its base type,
since the subtype must be usable anywhere the base type is usable
Dependency Inversion Principle
any dependency of an object should be provided externally instead of dependency internally created .
1- High-level modules should not depend on low-level modules .
2- Abstractions should not depend upon details. Details should depend upon abstractions.
Java Design Patterns book by Vaskaran Sarcar
https://sourcemaking.com/
The end
Anas alpure
Ad

More Related Content

What's hot (20)

PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Design patterns
Design patternsDesign patterns
Design patterns
Elyes Mejri
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
Jagath Bandara Senanayaka
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
Srikanth R Vaka
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Anuja Arosha
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patterns
op205
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
Priyanka Pradhan
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patterns
Malik Sajid
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
naveen kumar
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Pankhuree Srivastava
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
Rajiv Gupta
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
Umar Ali
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patterns
op205
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
Priyanka Pradhan
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patterns
Malik Sajid
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
naveen kumar
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
Rajiv Gupta
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
Umar Ali
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
Gaurav Tyagi
 

Similar to Design patterns (20)

Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Rafael Coutinho
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
Fahad A. Shaikh
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
Eliah Nikans
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
MD Sayem Ahmed
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
Java mcq
Java mcqJava mcq
Java mcq
avinash9821
 
C questions
C questionsC questions
C questions
parm112
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
Dang Tuan
 
How to design an application correctly ?
How to design an application correctly ?How to design an application correctly ?
How to design an application correctly ?
Guillaume AGIS
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
Savio Sebastian
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
Chris Eargle
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
Naga Muruga
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
Eliah Nikans
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
MD Sayem Ahmed
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
C questions
C questionsC questions
C questions
parm112
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
Dang Tuan
 
How to design an application correctly ?
How to design an application correctly ?How to design an application correctly ?
How to design an application correctly ?
Guillaume AGIS
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
Savio Sebastian
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
Chris Eargle
 
Ad

More from Anas Alpure (13)

WEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdfWEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdf
Anas Alpure
 
أنواع المحددات Css
أنواع المحددات Cssأنواع المحددات Css
أنواع المحددات Css
Anas Alpure
 
css flex box
css flex boxcss flex box
css flex box
Anas Alpure
 
css advanced
css advancedcss advanced
css advanced
Anas Alpure
 
css postions
css postionscss postions
css postions
Anas Alpure
 
CSS layout
CSS layoutCSS layout
CSS layout
Anas Alpure
 
intro to CSS
intro to CSSintro to CSS
intro to CSS
Anas Alpure
 
Web Design
Web DesignWeb Design
Web Design
Anas Alpure
 
Intro to HTML Elements
Intro to HTML ElementsIntro to HTML Elements
Intro to HTML Elements
Anas Alpure
 
HTML
HTMLHTML
HTML
Anas Alpure
 
البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات
Anas Alpure
 
مبادء في البرمجة
مبادء في البرمجةمبادء في البرمجة
مبادء في البرمجة
Anas Alpure
 
Google Maps Api
Google Maps ApiGoogle Maps Api
Google Maps Api
Anas Alpure
 
WEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdfWEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdf
Anas Alpure
 
أنواع المحددات Css
أنواع المحددات Cssأنواع المحددات Css
أنواع المحددات Css
Anas Alpure
 
Intro to HTML Elements
Intro to HTML ElementsIntro to HTML Elements
Intro to HTML Elements
Anas Alpure
 
البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات
Anas Alpure
 
مبادء في البرمجة
مبادء في البرمجةمبادء في البرمجة
مبادء في البرمجة
Anas Alpure
 
Ad

Recently uploaded (20)

Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 

Design patterns

  • 1. DP = scalable app = save time Anas alpure
  • 2. design patterns Creational Patterns: Structural Patterns: Behavioral Patterns: • Singleton Pattern • Abstract Factory Pattern • Prototype Pattern • Factory Method Pattern • Builder Pattern • Proxy Pattern • Flyweight Pattern • Bridge Pattern • Facade Pattern • Decorator Pattern • Adapter Pattern • Composite Pattern • Observer Pattern • Template Method Pattern • Command Pattern • Iterator Pattern • State Pattern • Mediator Pattern • Strategy Pattern • Chain of Responsibility Pattern • Visitor Pattern • Interpreter Pattern • Memento Pattern
  • 3. design patterns DP = scalable app = save time
  • 4. naming conventions in java class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc. method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc. variable name should start with lowercase letter e.g. firstName, orderNumber etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
  • 6. Singleton Patterns A particular class should have only one instance. we have made the constructor private so that we cannot instantiate in normal fashion. When we attempt to create an instance of the class, we are checking whether we already have one available copy. If we do not have any such copy, we’ll create it; otherwise, we’ll simply reuse the existing copy. getInstance GoF Definition: Ensure a class only has one instance, and provide a global point of access to it.
  • 7. Flyweight Pattern GoF Definition: Use sharing to support large numbers of fine-grained objects efficiently. we try to minimize memory usage by sharing data as much as possible. Map<String, IRobot> shapes = new HashMap<String, IRobot>(); getInstance(String str) { if (shapes.containsKey(str)){ } else { switch (str){ } } }
  • 8. Prototype Pattern(cloning) GoF Definition: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. - prototype pattern provides an alternative method for instantiating new objects by copying or cloning an instance of an existing one.
  • 9. Builder Pattern 0..10..1 0..1 The Director class constructs the complex object using the Builder interface. parts class Car implements IBuilder { private Product product = new Product(); @Override public void BuildBody() { product.Add("This is a body of a Car") ; } @Override public void InsertWheels() { product.Add("4 wheels are added"); } @Override public void AddHeadlights() { product.Add…... } @Override public Product GetVehicle() { return product; } } class Director { IBuilder myBuilder; public void Construct(IBuilder builder) { myBuilder=builder; myBuilder.BuildBody(); myBuilder.InsertWheels(); myBuilder.AddHeadlights(); } } // main method IBuilder carBuilder = new Car(); // Making Car director.Construct(carBuilder); Product p1 = carBuilder.GetVehicle(); p1.Show(); GoF Definition: Separate the construction of a complex object from its representation parts
  • 10. Observer Patterns GoF Definition: Define a one-to-many dependency between objects so that when one object (subject) changes state, all its dependents(observers) are notified and updated automatically.
  • 12. Push and Pull • Push algorithm: When the Subject (Publisher) updates the Observers (Subscribers), it sends the data to all of them even if they don’t need it, so it is a negative aspect of the algorithm. • Pull algorithm: When the Subject (Publisher) updates the Observers (Subscribers), it only tells them that the data is changed, so Observers (Subscribers) retrieve it if they need the data. • Pull algorithm is better.
  • 13. Factory Method Pattern Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. Factory Pattern "I want red car" ‫المبدء‬‫لـ‬ ‫األول‬SOLID‫مبدء‬‫المسؤلية‬‫الوحيدة‬ GoF Definition: Define an interface for creating an object, but let subclasses decide which class to instantiate. The factory method lets a class defer instantiation to subclasses. is also known as Virtual Constructor.
  • 14. Abstract Factory Patterns(super-factory ) abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories Provides an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes. That means Abstract Factory lets a class returns a factory of classes. So, this is the reason that Abstract Factory Pattern is one level higher than the Factory Pattern. is also known as Kit.
  • 15. 0..1 Proxy PatternsGoF Definition: Provide a surrogate or placeholder for another object to control access to it. ‫نائب‬ A proxy is an object that can be used to control access to another object.
  • 16. Adapter Patterns GoF Definition: Convert the interface of a class into another interface that clients expect. Adapter pattern works as a bridge between two incompatible interfaces. - Wrap an existing class with a new interface. <<Class>> FacebookApi Do_post(msg) Get_post() <<interface>> SocialMedia post(msg) getPost() <<Class>> facebookAdapter +facebookApi post(msg) getPost() Adaptee Adaptor 0..1
  • 17. Template Method Patterns / abstract GoF Definition: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  • 18. 0..1 We can select the behavior of an algorithm dynamically at runtime. ‫يحقق‬‫مبدء‬OCP Strategy Patterns (Or, Policy Patterns) /Context 1 class to many behaviors 1 context to family of behaviors [1:many relationship]
  • 19. context ‫بها‬ ‫خاص‬ ‫وسلوك‬ ‫متلف‬ ‫بشكل‬ ‫تعرض‬ ‫بطة‬ ‫كل‬. enables selecting an algorithm at runtime. The strategy pattern -defines a family of algorithms, -encapsulates each algorithm, and -makes the algorithms interchangeable within that family. Strategy lets the algorithm vary independently from clients that use it.
  • 20. Decorator Patterns You would use it when you want the capabilities of inheritance with subclasses, but you need to add functionalities at run time. attach a flexible additional responsibilities to an object dynamically"
  • 21. Decorator Patterns Interface i = new O1(new O2(new O3())); Component AbstractDecorator base Component ConcreteEX1 ConcreteEX2 0..1 ‫المجرد‬ ‫الكلس‬ ‫يمتلك‬AbstractDecorator‫الوكيل‬ ‫دور‬ ‫من‬ ‫مقبض‬ ‫يمتلك‬ ‫حيث‬Component‫المقبض‬ ‫هذا‬ ‫األنواع‬ ‫من‬ ‫أي‬ ‫الى‬ ‫يشير‬ ‫ان‬ ‫يمكن‬‫الثالئة‬‫ال‬EX1,EX2,base.. ‫تنفيذ‬ ‫عند‬EX2.doJob() ‫لدالة‬ ‫التنفيذ‬ ‫فان‬doJob‫في‬ ‫الموجودة‬EX2 ‫التالية‬ ‫التعليمة‬ ‫تحوي‬ ‫والتي‬super.doJob(); ‫الـ‬super‫ل‬EX2‫هو‬AbstractDecorator ‫في‬ ‫يحوي‬ ‫والذي‬doJob‫به‬ ‫الخاصة‬ ‫الوصول‬ ‫حتا‬ ‫االمر‬ ‫يتكرر‬ ‫وهكذا‬‫لل‬base ‫تحوي‬ ‫ال‬ ‫التي‬ ‫و‬super.doJob();‫دالة‬ ‫في‬doJob‫اب‬ ‫لديها‬ ‫ليس‬ ‫الن‬(interface) ‫ملف‬ ‫في‬ ‫موجود‬ ‫الكود‬decorator anas.java Decorator‫من‬ ‫خاصة‬ ‫حالة‬Composite(‫شجري‬ ‫تمثيل‬tree)
  • 22. abstract class Component { public abstract void doJob(); } //base calss class ConcreteComponent extends Component { @Override public void doJob() { System.out.println(" this base job"); } } //Decorator abstract class AbstractDecorator extends Component { protected Component com; public AbstractDecorator(Component c) { com = c; } public void doJob() { if (com != null) { com.doJob(); } } } //extra class1 class ConcreteDecoratorEx_1 extends AbstractDecorator { public ConcreteDecoratorEx_1(Component c) { super(c); } public void doJob() { System.out.println("** Ex-1 START**"); super.doJob(); System.out.println("** EX-1 end**"); } } Decorator Patterns Attach additional responsibilities to an object dynamically. add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
  • 23. interface AbstractFile { void ls(); } class Directory implements AbstractFile { private String name; private ArrayList includedFiles=new ArrayList(); public Directory(String name) { this.name = name; } public void add(Object obj) { includedFiles.add(obj); } public void ls() { System.out.println(name); for (Object includedFile : includedFiles) { } } } Composite Patterns we make a composite object when we have many objects with common functionalities. This relationship is also termed a “has-a” relationship among objects. Any tree structure in computer science can follow a similar concept. 0 ..* Directory Name:String List< AbstractFile > Add() Remove() getDetails() AbstractFile getDetails() file getDetails()
  • 24. GoF Definition: Compose objects into tree structures to represent part-whole hierarchies. The composite pattern lets clients treat individual objects and compositions of objects uniformly.
  • 25. Command Patterns is also known as Action 0..1 ‫الغرض‬ ‫لدينا‬Receiver‫مهام‬ ‫عدة‬ ‫بإنجاز‬ ‫يقوم‬ ‫الغرض‬ ‫ولدينا‬Invoke‫السابقة‬ ‫المهام‬ ‫ينفذ‬ ‫ان‬ ‫يريد‬ ‫الطالب‬ ‫لفصل‬Invoke‫المطلوب‬ ‫عن‬Receiver‫النموذج‬ ‫هذا‬ ‫يقترح‬: ‫في‬ ‫مهمة‬ ‫لكل‬ ‫كلس‬ ‫انشاء‬Receiver‫من‬ ‫ترث‬Icommand ‫و‬Invoke‫تستقبل‬ ‫دالة‬ ‫يحقق‬‫بارمتر‬Icommand ‫يمكن‬ ‫وبالتالي‬‫لل‬‫ـ‬Invokeً‫ال‬‫مث‬ ‫عنها‬ ‫والتراجع‬ ‫تنفيذها‬ ‫تم‬ ‫التي‬ ‫األخيرة‬ ‫المهام‬ ‫معرفة‬.....
  • 26. RemoteControl //Invoker public class RemoteControl{ private Command command; public void setCommand(Command command){ this.command = command; } public void pressButton(){ command.execute(); } } //Receiver public class Light{ private boolean on; public void switchOn(){ on = true; } public void switchOff(){ on = false; } } RemoteControl control = new RemoteControl(); Light light = new Light(); Command lightsOn = new LightsOnCommand(light); Command lightsOff = new LightsOffCommand(light); //switch on control.setCommand(lightsOn); control.pressButton(); //Concrete Command public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light){ this.light = light; } public void execute(){ light.switchOn(); } } Client
  • 27. Command Patterns is also known as Action GoF Definition: Encapsulate a request as an object, and pass it to invoker object. •It separates the object that invokes the operation from the object that actually performs the operation. •It makes easy to add new commands, ‫يستخدم‬Command‫حيث‬ ‫مهام‬ ‫عدة‬ ‫لتنفيذ‬‫في‬ ‫مهمة‬ ‫كل‬ ‫يغلف‬object‫عن‬ ‫تراجع‬ ‫عمل‬ ‫يمكن‬ ‫وأيضا‬ ‫به‬ ‫نفذت‬ ‫التي‬ ‫بالترتيب‬ ‫يحفظها‬ ‫و‬Undo‫و‬Redo <<interface>> ICommand +execute() +undo() //redo 0 ..* push( Icommand c ){ c. execute(); redoStack.clear(); undoStack.push(c); } CommandStack‫عن‬ ‫مسؤول‬ ‫الـ‬ ‫إدارة‬commands‫ونقلها‬ ‫المكدسات‬ ‫بين‬ <<Class>> CommansStack +execute() +undo() +push(Icommand c) - undoStack <<Icommand>> - redoStack <<Icommand>> Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request. Problem
  • 28. Memento Pattern provides the ability to restore an object to its previous state (undo via rollback). The memento pattern is implemented with three objects: • the originator , • a caretaker , • a memento . - Our aim is to save the state of an object(originator), so that in the future, we can go back to the specified state. - the memento pattern operates on a single object. 0..1 0..1 class Originator { private String state; Memento m; public void setState(String state) { this.state = state; } // Creates memento public Memento OriginatorMemento() { m = new Memento(state); return m; } public void Revert(Memento memento) { state = memento.getState(); } }
  • 30. Visitor Pattern / APIs This pattern helps us to add new functionalities to an existing object structure in such a way that the old structure remains unaffected by these changes. So, we can follow the open/close principle here : (extension allowed but modification disallowed for entities like class, function, modules, etc.). ‫ممنوع‬ ‫التعديل‬ ‫و‬ ‫مسموحة‬ ‫اإلضافة‬ Plugging into public APIs is a common example. Then a client can perform his desired operations without modifying the actual code (with a visiting class). many classes to many behaviors[many:many relationship] Visitor lets you define a new operation without changing the classes
  • 31. API
  • 32. <<interface>> Iitem +getDiscount(DiscountPolicy d) +get_price() <<Class>> Book +getDiscount() +get_price() <<Class>> Pen +getDiscount() +get_price() <<interface>> IDiscountPolicy +getDiscount(Book b) +getDiscount(Pen p) << Class >> DiscountPolicy +getDiscount(Book b) +getDiscount(Pen p) IVisitor @Override public float getDiscount (DiscountPolicy d) { return d. getDiscount(this); } Overloading
  • 33. 0..1 API Strategy patternvisitor pattern ‫تركيب‬ ‫عالقة‬ ‫اعتمادية‬ ‫عالقة‬ 1 class to many behaviors [1:many relationship] many classes to many behaviors [many:many relationship] We can select the behavior of an algorithm dynamically at runtimeadd new functionalities to an existing object structure ‫مثل‬ ‫جديد‬ ‫كلس‬ ‫إضافة‬ ‫عند‬MyClass2 ‫نضيف‬ ‫فقط‬override function visit(MyClass2) ‫في‬Visitor class ‫التنفيذ‬ ‫اثناء‬ ‫للتغير‬ ‫قابل‬(dynamically) ‫فقط‬ ‫جديد‬ ‫سلوك‬ ‫إضافة‬ ‫يمكن‬
  • 35. ON OFF GoF Definition: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • 36. Iterator Pattern Provide a way to access the elements of an aggregate object sequentially. it doesn’t care which data structure is used . ‫أي‬aggregate object‫محتواه‬ ‫يعيد‬ ‫ان‬ ‫يريد‬ ‫عبر‬Iterator‫الوجهة‬ ‫يطبق‬Iaggregate ‫الطريقة‬ ‫تعريف‬ ‫ويعيد‬CreateIterator() ‫نوع‬ ‫من‬ ‫كائن‬ ‫تعيد‬ ‫التي‬Iterator ‫الدوال‬ ‫تعريف‬ ‫ويعيد‬ ‫ببرمجته‬ ‫يقوم‬"First,Next,…." we Can combine the iterator pattern with the composite pattern Need to "abstract" the traversal of wildly different data structures Problem
  • 37. Mediator Pattern GoF Definition: Define an object that encapsulates how a set of objects interacts. The advantage of using such a mediator is that we can reduce the direct interconnections among the objects and thus lower the coupling. “ many-to-many” relationship ” ChatRoom Colleague 0..* <<abstract>> sendMessage(message, sender) ‫الكل‬ ‫الى‬ ‫رسالة‬ ‫ارسال‬ ‫يستطيع‬ ‫عضو‬ ‫كل‬many-to-many=>Mediator ‫ارسال‬ ‫يستطيع‬ ‫عضو‬‫رسالى‬‫للكل‬one-to-many=>Observer DesktopColleague MobileColleague Imediator
  • 39. • ColleagueBase: this is the abstract class (or interface) for all concrete colleagues. It has a protected field that holds a reference to the mediator object. • ConcreteColleague: this is the implementation of the ColleagueBase class. Concrete colleagues are classes which communicate with each other. • MediatorBase: this is the abstract class for the mediator object. This class contains methods that can be consumed by colleagues. • ConcreateMediator: this class implements communication methods of the MediatorBase class. This class holds a reference to all colleagues which need to communicate.
  • 40. The Model View Controller ( MVC ) : a Composed Pattern. Model: - Contains data. - Encapsulates application state. - Responds to state queries/updates. - Exposes application functionality. View: - Renders the model. - Allows Controller to select view. - Sends user input to the Controller. Controller: - Defines application behavior. - Maps user actions to Model updates. Structure Pattern
  • 41. OOP Principles SOLIDsingle responsibility principle : A class should have only one reason to chang (factory) The Open-Closed Principle: Software Entities Should Be Open For Extension, Yet Closed For Modification ( Visitor – Strategy ) The Single Choice Principle: (Singleton) The Liskov Substitution Principle(LSP) ” ‫استبدال‬‫لسكوف‬ ”: Functions That Use References To Base (Super) Classes Must Be Able To Use Objects Of Derived(Sub) Classes Without Knowing It If a function does not satisfy the LSP, then it probably makes explicit reference to some or all of the subclasses of its superclass. Such a function also violates the Open-Closed Principle, since it may have to be modified whenever a new subclass is created. A subtype must have no more constraints than its base type, since the subtype must be usable anywhere the base type is usable Dependency Inversion Principle any dependency of an object should be provided externally instead of dependency internally created . 1- High-level modules should not depend on low-level modules . 2- Abstractions should not depend upon details. Details should depend upon abstractions.
  • 42. Java Design Patterns book by Vaskaran Sarcar https://sourcemaking.com/ The end Anas alpure