0% found this document useful (0 votes)
23 views45 pages

Design Pattern June 23

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views45 pages

Design Pattern June 23

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Design Principles and

Patterns
Anmol Parikh (MCP)
Harsh Thaker (CSX)
Mitesh Mehta (MF)
Agenda

● SOLID
● Creational
● Behavioral
● Structural
● Case Studies/Live Examples
○ Checkout
○ Ultron/Optimus

2
SOLID

S : Single Responsibility Principle (SRP)


O : Open closed Principle (OSP)
L : Liskov substitution Principle (LSP)
I : Interface Segregation Principle (ISP)
D : Dependency Inversion Principle (DIP)

● Makes software modular


● Easy to understand, debug and refactor

3
Single Responsibility Principle ( SRP )
“A class should have only one reason to change”
public void getLoanInterestInfo(String loanType) {
public class BankService { if (loanType.equals("homeLoan")) {
//do some job
public long deposit(long amount, string }
accountno) { if (loanType.equals("personalLoan")) {
//deposit amount //do some job
return 0; }
} if (loanType.equals("car")) {
//do some job
public long withdraw(long amount, string }
accountno) { }
//withdraw amount
return 0; public void sendOTP(String medium) {
} if (medium.equals("email")) {
//write email related logic
public void printpassbook() { //use JavaMailSenderAPI
//update transaction info in passbook }
} }
}

4
Single Responsibility Principle ( SRP )
public class NotificationService {
public class PrinterService{
public void sendOTP(String medium) {
public void printPassbook() {
if (medium.equals("email")) {
//update transaction info in passbook
//write email related logic
}
//use JavaMailSenderAPI
}
}
}
public class LoanService{
}
void getLoanInterestInfo(String loanType) {
if (loanType.equals("homeLoan")) {
//do some job
}
if (loanType.equals("personalLoan")) {
//do some job
}
if (loanType.equals("car")) {
//do some job
}
}
}

5
Open Closed Principle ( OCP )

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for
modification”

public class NotificationService {


public void sendOTP(String medium) {
if (medium.equals("email")) {
//write email related logic
//use JavaMailSenderAPI
}
}
}

6
Open Closed Principle ( OCP )

public interface NotificationService {


public void sendOTP(String medium);
}

public class EmailNotification implements NotificationService {


public void sendOTP(String medium) {
// write Logic using JavaEmail api
}
}

public class MobileNotification implements NotificationService {


public void sendOTP(String medium) {
// write Logic using Twilio SMS API
}
}

7
Liskov’s Substitution Principle ( LSP )
“Derived or child classes must be substitutable for their base or
parent classes” public class Facebook extends SocialMedia {

public void chatWithFriend() {


//logic
public abstract class SocialMedia { }
public void publishPost(Object post) {
public abstract void chatWithFriend(); //logic
}
public abstract void publishPost(Object post); public void sendPhotosAndVideos() {
//logic
public abstract void sendPhotosAndVideos(); }
public void groupVideoCall(String...
public abstract void groupVideoCall(String... users); users) {
} //logic
}
}

8
Liskov’s Substitution Principle ( LSP )

public interface SocialMedia {


public void chatWithFriend();
public void sendPhotosAndVideos()
}

public interface PostManager {


public void publishPost(Object post);
}

public interface VideoCallManager {


public void groupVideoCall(String...users);
}

9
Interface Segregation Principle ( ISP )
“Do not force any client to implement an interface which is irrelevant to them“

public interface UPIPayments {

public void payMoney();

public void getScratchCard();

public void getCashBackAsCreditBalance();

10
Interface Segregation Principle ( ISP )
“do not force any client to implement an interface which is irrelevant to them“

public interface CashbackManager {

public void getCashBackAsCreditBalance();

11
Dependency Inversion ( DI )
“ Use abstractions instead of concrete implementations “ public class ShoppingMall {
private DebitCard debitCard;

public class DebitCard { public void doPayment(Object order, int


amount) {
public void doTransaction(int amount) {
debitCard.doTransaction(amount);
System.out.println("tx done with DebitCard");
}
}
public static void main(String[] args) {
}
DebitCard debitCard = new DebitCard();
public class CreditCard {
ShoppingMall shoppingMall = new
public void doTransaction(int amount) {
ShoppingMall(debitCard);
System.out.println("tx done with CreditCard");
shoppingMall.doPayment("some order",
} 5000);
} }
}

12
Dependency Inversion ( DI )

public interface BankCard {


public void dotransaction(int amount);
}

public class Creditcard implements BankCard {


public void dotransaction(int amount) {
System.out.println("tx done with Credit card");
}
}

public class Debitcard implements BankCard {


public void doTransaction(int amount) {
System.out.println("tx done with Debit card");
}
}

13
Dependency Inversion ( DI )

public class ShoppingMall {


private BankCard bankCard;
public ShoppingMall(BankCard bankCard) {
this.bankCard = bankCard;
}
public void doPayment(Object order, int amount) {
bankCard.doTransaction(amount);
}
public static void main(String[] args) {
BankCard bankCard = new CreditCard();
ShoppingMall shoppingMall1 = new ShoppingMall(bankCard);
shoppingMall1.doPayment("do some order", 10000);
}
}

14
KISS , DRY, YAGNI
1. KISS : Keep it Simple and Stupid
Make your code simple and easy to understand

2. DRY : Do Not Repeat Yourself


Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

3. YAGNI : You aren’t gonna need it


Always implement things when you actually need them, never when you just foresee that you need them.

15
Creational

Design patterns are tried and tested solutions to common problems in software design. They are like
pre-made blueprints that you can customize to solve a recurring design problem in your code.

Creational design patterns provide various object creation mechanisms, which increase flexibility and
reuse of existing code.
• Factory
• Abstract Factory
• Singleton
• Builder
• Prototype

16
Factory

17
Factory public class EmailNotification implements Notification

public interface Notification { {


@Override
void notifyUser();
public void notifyUser() {
}
// TODO Auto-generated method stub
System.out.println("Sending an e-mail
public class SMSNotification implements Notification
notification");
{
}
@Override
}
public void notifyUser() {
// TODO Auto-generated method stub public class PushNotification implements Notification {
System.out.println("Sending an SMS notification"); @Override
} public void notifyUser() {
} // TODO Auto-generated method stub
System.out.println("Sending a push notification");
}
}

18
Factory
public class NotificationFactory {
public Notification createNotification(String channel) {
if (channel == null || channel.isEmpty())
return null;
switch (channel) {
case "SMS":
return new SMSNotification();
case "EMAIL":
return new EmailNotification();
case "PUSH":
return new PushNotification();
default:
throw new IllegalArgumentException("Unknown channel " + channel);
}
}
}

public class NotificationService {


public static void main(String[] args) {
NotificationFactory notificationFactory = new NotificationFactory();
Notification notification = notificationFactory.createNotification("SMS");
notification.notifyUser();
}
}

19
Abstract Factory

20
Singleton

21
Builder

22
Prototype

23
Behavioral Design Patterns
Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between
objects.
• Chain Of Responsibility
• Command
• Iterator
• Mediator
• Memento
• Observer
• State
• Strategy
• Template Method
• Visitor

24
Behavioral - Chain Of Responsibility
Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each
handler decides either to process the request or to pass it to the next handler in the chain.

25
Behavioral - Command
Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This
transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.

26
Behavioral - Visitor
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.

27
Behavioral - Strategy
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their
objects interchangeable.

28
Structural Design Patterns
Structural design patterns explain how to assemble objects and classes into larger structures, while keeping
these structures flexible and efficient.
• Adapter
• Bridge
• Composite
• Decorator
• Facade
• Flyweight
• Proxy

29
Structural- Adapter
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.

30
Structural- Decorator
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects
that contain the behaviors.

31
Structural- Facade
Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.

32
Structural- Proxy
Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original
object, allowing you to perform something either before or after the request gets through to the original object.

33
Checkout
What is Checkout ?

● Checkout is one-stop-shop for all payment aggregations on PhonePe ecosystem


required by Android and iOS apps.

● Tenants like Nexus / MF / Switch integrate with checkout for their use-cases

35
Checkout Flow

36
Pre Checkout Flow

37
Drawbacks

● Each service used to integrate with Payments

● Heterogeneous modelling causing maintenance issues

● Sensitive data getting passed to all tenant services

38
Post Checkout Flow

39
Benefits

● Homogeneous Workflow for all payment flows


Payments can put authn/authz for a single client

● Single modelling abstraction for the app

● Multi DC Support

● Central Fees

40
Risks

● Single Point Of Failure


○ Autoscaler
○ A/B Deployment
○ Strict code change sign off process

● Degradation due to latency of Tenants


e.g Nexus - latency due to external service provider
○ Separate service deployment for tenant

41
Design Patterns ( Applicable for most orchestrators )

● Facade layer for clients for all payments

● Tenanted platform( Tenant degradation, concurrency mgmt etc )

● Polymorphism
App -> Checkout Service : options/init/confirm

● Chain of Responsibility

● Singleton

● Visitor Pattern

42
Design Patterns

● Factory Pattern
Client Factory to get http client of each tenant
tenantHttpConfigs:
MutualFundClient:
clientId: MutualFundClient
usingZookeeper: true
serviceName: mutualfund
environment: stage
host: mutualfund.traefik.stg.phonepe.com
port: 80

VisanaClient:
clientId: VisanaClient
usingZookeeper: false
serviceName: visana
environment: stage
host: visana.stgob.phonepe.az6
port: 443

● Registry with Tenant and Config


tenantInitPath:
MUTUAL_FUND : "/v1/service/init"
VISANA : "/v1/insurance/init"
tenantConfirmPath:
MUTUAL_FUND : "/v1/service/init/confirm"
VISANA : "/v1/insurance/init/confirm"
tenantPaymentOptionPath:
MUTUAL_FUND : "/v1/service/payment/constraints"
VISANA : "/v1/insurance/payment/constraints"

43
Design Patterns

Abstract Factory Design Pattern

Command Factory

Inline Factory
className
methodName

Client Factory
httpClient
endpoint

44
Thank you

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy