Created
September 3, 2024 14:40
-
-
Save jonathborg/defe3159f2fe31a3993488f7b32520da to your computer and use it in GitHub Desktop.
Implementation of adapter pattern with Factory (optional)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type CustomInfo = { | |
name: string; | |
email: string; | |
phoneNumber: string; | |
}; | |
interface CreditManagerSystem { | |
getCreditLimitForCustomer(customerId: string): number; | |
getCustomerInfo(customerId: string): CustomInfo; | |
} | |
class SGCredAdapter implements CreditManagerSystem { | |
getCreditLimitForCustomer(customerId: string): number { | |
return 1000; | |
} | |
getCustomerInfo(customerId: string): CustomInfo { | |
return { | |
email: "customer@sgcred.com.br", | |
name: "Customer from SGCred", | |
phoneNumber: "123456789" | |
} | |
} | |
} | |
class BetaAdapter implements CreditManagerSystem { | |
getCreditLimitForCustomer(customerId: string): number { | |
return 5001; | |
} | |
getCustomerInfo(customerId: string): CustomInfo { | |
return { | |
email: "customer@beta.com.br", | |
name: "Customer from Beta™", | |
phoneNumber: "999999999" | |
} | |
} | |
} | |
class CustomerService { | |
constructor(private readonly creditManager: CreditManagerSystem) {} | |
getLimit(customerId: string): number { | |
return this.creditManager.getCreditLimitForCustomer(customerId); | |
} | |
getInfo(customerId: string): CustomInfo { | |
return this.creditManager.getCustomerInfo(customerId); | |
} | |
} | |
class CreditManagerFactory { | |
static create(type: "sgcred" | "beta"): CreditManagerSystem { | |
switch (type) { | |
case "sgcred": | |
return new SGCredAdapter(); | |
case "beta": | |
return new BetaAdapter(); | |
default: | |
throw new Error("Invalid type"); | |
} | |
} | |
} | |
const creditManagerSystem = CreditManagerFactory.create("beta"); | |
const customerService = new CustomerService(creditManagerSystem); | |
console.log(customerService.getInfo("123")); | |
console.log(customerService.getLimit("123")); // 5001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment