SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
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();
}
}
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

Weitere ähnliche Inhalte

Was ist angesagt?

PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael 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 PatternNishith Shukla
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire 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 Patternsop205
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanPriyanka Pradhan
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patternsMalik Sajid
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael 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 PatternsSameh Deabes
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 

Was ist angesagt? (20)

PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
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
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
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
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patterns
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
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
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 

Ähnlich wie Design patterns

Java design patterns
Java design patternsJava design patterns
Java design patternsShawn 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 PatternsLalit Kale
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
C questions
C questionsC questions
C questionsparm112
 
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_argumentsRuth 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, angularjsRavi Bhadauria
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design PatternsDang 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 2Savio 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.docxdanhaley45372
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of PatternsChris Eargle
 

Ähnlich wie Design patterns (20)

Java design patterns
Java design patternsJava design patterns
Java design patterns
 
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
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Java mcq
Java mcqJava mcq
Java mcq
 
C questions
C questionsC questions
C questions
 
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
 
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
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
 
How to design an application correctly ?
How to design an application correctly ?How to design an application correctly ?
How to design an application correctly ?
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
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
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
 

Mehr von Anas Alpure

WEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdfWEB DEVELOPMENT DIPLOMA v1.pdf
WEB DEVELOPMENT DIPLOMA v1.pdfAnas Alpure
 
أنواع المحددات Css
أنواع المحددات Cssأنواع المحددات Css
أنواع المحددات CssAnas Alpure
 
Intro to HTML Elements
Intro to HTML ElementsIntro to HTML Elements
Intro to HTML ElementsAnas Alpure
 
البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات البرمجيات و الانترنيت و الشبكات
البرمجيات و الانترنيت و الشبكات Anas Alpure
 
مبادء في البرمجة
مبادء في البرمجةمبادء في البرمجة
مبادء في البرمجةAnas Alpure
 

Mehr von Anas Alpure (13)

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

Kürzlich hochgeladen

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Kürzlich hochgeladen (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

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(); } }
  • 29.
  • 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