Created
July 31, 2019 21:45
-
-
Save betandr/a8adfa00a194325ed12ac9146c8ce82d to your computer and use it in GitHub Desktop.
Encapsulation with an interface
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
package account | |
import ( | |
"errors" | |
) | |
type CheckingAccount struct { | |
balance int | |
} | |
func (a *CheckingAccount) Pay(amount int) error { | |
if a.balance-amount < 0 { | |
return errors.New("not enough funds") | |
} | |
a.balance = a.balance - amount | |
return nil | |
} | |
func (a *CheckingAccount) Deposit(amount int) { | |
a.balance = a.balance + amount | |
} | |
func (a *CheckingAccount) Balance() int { | |
return a.balance | |
} | |
func CreateAccount() *CheckingAccount { | |
return &CheckingAccount{} | |
} | |
// ----------------- | |
package main | |
import ( | |
"fmt" | |
"account" | |
) | |
type Account interface { | |
Pay(amount int) error | |
Deposit(amount int) | |
Balance() int | |
} | |
func main() { | |
var acc Account | |
acc = account.CreateAccount() | |
acc.Deposit(18) | |
fmt.Printf("balance is: %d\n", acc.Balance()) | |
acc.Pay(10) | |
fmt.Printf("balance is: %d\n", acc.Balance()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment