Skip to content

Instantly share code, notes, and snippets.

View hernanhrm's full-sized avatar
🏠
Working from home

Hernan Reyes hernanhrm

🏠
Working from home
View GitHub Profile
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:PutObjectAcl"
func main() {
// unlike the Strategy Pattern implementation
// here we don't have to initialize our strategies
// because all the logic to pay is inside the Purchase Class
purchase := NewPurchase()
fmt.Println("Enter the payment method you want to use (PayPal, CreditCard or Bank: ")
var paymentMethod string
fmt.Scanln(&paymentMethod)
type Purchase struct{}
func NewPurchase() Purchase {
return Purchase{}
}
func (p Purchase) Process(paymentMethod string) error {
// you can add logic to query and validate the order
switch paymentMethod {
type Bitcoin struct {}
func NewBitcoin() Bitcoin {
return Bitcoin{}
}
func (b Bitcoin) Pay() error {
// Here you'll add the logic to pay with a Bitcoin
fmt.Println("Processing purchase with Bitcoin...")
func main() {
// we initialize our strategies
purchase := NewPurchase()
purchase.RegisterStrategy("PayPal", NewPaypal())
purchase.RegisterStrategy("CreditCard", NewCreditCard())
purchase.RegisterStrategy("Bank", NewBank())
fmt.Println("Enter the payment method you want to use (PayPal, CreditCard or Bank: ")
var paymentMethod string
fmt.Scanln(&paymentMethod)
type Bank struct {}
func NewBank() Bank {
return Bank{}
}
func (b Bank) Pay() error {
// Here you'll add the logic to pay with a bank
fmt.Println("Processing purchase with Bank...")
type CreditCard struct {}
func NewCreditCard() CreditCard {
return CreditCard{}
}
func (c CreditCard) Pay() error {
// Here you'll add the logic to pay with credit card
fmt.Println("Processing purchase with CreditCard...")
// PayPal implementation of the PaymentMethodStrategy interface
// with the necessary logic to pay with PayPal
type PayPal struct {}
func NewPaypal() PayPal {
return PayPal{}
}
func (p PayPal) Pay() error {
// Here you'll add the logic to pay with PayPal
// Purchase is our goal/context which maintains a reference to all the
// possible strategies that the client can use to pay
type Purchase struct {
// we create a map to save all the PaymentMethodStrategy implementations
// so in runtime, when a client execute the Process method
// the client can choose the strategy to use
paymentMethodStrategies map[string]PaymentMethodStrategy
}
func NewPurchase() Purchase {
// PaymentMethodStrategy will let us interchange
// the payment method in the context
type PaymentMethodStrategy interface {
Pay() error
}