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"
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.
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
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